Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webpack2 and react-toolbox #662

Closed
KeKs0r opened this issue Jul 22, 2016 · 15 comments
Closed

Webpack2 and react-toolbox #662

KeKs0r opened this issue Jul 22, 2016 · 15 comments

Comments

@KeKs0r
Copy link

KeKs0r commented Jul 22, 2016

Hi,

I am currently adding react-toolbox to my project, which is using webpack 2. I have used it before and did not have any issues. But in the new project, it seems I can't get my webpack config to properly work with react-toolbox.

I am always running into this error:

/Users/marc/Sites/react-universally/node_modules/react-toolbox/lib/tabs/theme.scss:1
(function (exports, require, module, __filename, __dirname) { @import "../colors";
                                                              ^
SyntaxError: Unexpected token ILLEGAL
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:513:28)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/marc/Sites/react-universally/node_modules/react-toolbox/lib/tabs/index.js:18:14)
    at Module._compile (module.js:541:32)

My webpack configuration looks like this:

{ target: 'web',
  node: { __dirname: true, __filename: true },
  externals: [],
  devtool: 'source-map',
  entry: 
   { main: 
      [ 'react-hot-loader/patch',
        'webpack-hot-middleware/client?reload=true&path=http://localhost:8006/__webpack_hmr',
        '/Users/marc/Sites/react-universally/src/index.js' ] },
  output: 
   { path: '/Users/marc/Sites/react-universally/build/client',
     filename: '[name].js',
     chunkFilename: '[name]-[chunkhash].js',
     publicPath: '/',
     libraryTarget: 'var' },
  resolve: 
   { modules: [ '/Users/marc/Sites/react-universally/src', 'node_modules' ],
     extensions: [ '.js', '.jsx', '.json', '.scss' ] },
  plugins: 
   [ DefinePlugin { definitions: [Object] },
     AssetsWebpackPlugin { options: [Object], writer: [Function: queuedWriter] },
     NoErrorsPlugin {},
     HotModuleReplacementPlugin { multiStep: undefined, fullBuildTimeout: 200 } ],
  module: 
   { loaders: 
    [
       { test: /\.jsx?$/,
          loader: 'babel-loader',
          exclude: [ /node_modules/, '/Users/marc/Sites/react-universally/build' ],
          query: { 
            env: 
              {
                development: {
                  plugins: ['react-hot-loader/babel'],
                },
              }, 
            presets: [
                // JSX
                'react',
                // Webpack 2 includes support for es2015 imports, therefore we used this
                // modified preset.
                'es2015-webpack',
                //Added Stage 0 for destructor
                'stage-0'
              ],
             } },
        { test: /\.json$/, loader: 'json-loader' },
        { test: /\.css$/, loaders: [ 'style-loader', { loader: 'css-loader', query: { sourceMap: true } }, ] },
        { test: /\.scss$/,
          exclude: /(react-toolbox)/,
          loaders: 
           [ 'style',
             'css?sourceMap&-minimize',
             'postcss',
             'sass?sourceMap' ] },
        { test: /\.scss$/,
          include: /(react-toolbox)/,
          loaders: 
           [ 'style',
             'css?sourceMap&-minimize&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
             'postcss',
             'sass?sourceMap',
             'toolbox' ] },
        { test: /\.font$/, loaders: [ 'style', 'css', 'fontgen' ] },
        { test: /\.(png|jpg|gif)$/, loader: 'url?limit=8192' } 
      ]
    }
  sassLoader: 
   { includePaths: 
      [ '/Users/marc/Sites/react-universally/src/styles',
        '/Users/marc/Sites/react-universally/node_modules' ] },
  postcss: 
   [ Processor {
       version: '5.1.0',
       plugins: [Object],
       postcssPlugin: 'cssnano',
       postcssVersion: '5.1.0' } ],
  toolbox: { theme: './src/style/themes/toolbox.scss' } }
@node-monk
Copy link

Im also getting this error

webpack.config.js

var path = require('path');
var webpack = require('webpack');
var AssetsPlugin = require('assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

var DEBUG = !(process.env.NODE_ENV === 'production');
var env = {
  NODE_ENV: process.env.NODE_ENV,
  API_BASE_URL: process.env.API_BASE_URL
};

var config = {
  devtool: DEBUG ? 'cheap-module-eval-source-map' : false,
  entry: {
    app: './app/app',
    vendor: [
      'react',
      'react-router',
      'redux',
      'react-dom',
      'lodash',
      'bluebird',
      'humps',
      'history'
    ]
  },
  resolve: {
    extensions: ['', '.scss', '.css', '.js', '.json'],
    modulesDirectories: [
      'node_modules',
      path.resolve(__dirname, './node_modules')
    ],
    root: [ path.join(__dirname, 'app') ]
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: DEBUG ? '[name].js' : '[name].[chunkhash].js'
  },
  plugins: [
    new ExtractTextPlugin('react-toolbox.css', { allChunks: true }),
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(env)
    })
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        include: __dirname
      },{
        test: /(\.scss|\.css)$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass','sass')
      }
    ]
  }
  // sassLoader: {
  //   data: '@import "theme/_config.scss";',
  //   includePaths: [path.resolve(__dirname, './app')]
  // }
};


if (DEBUG) {
  config.entry.dev = [
    'webpack-dev-server/client?http://localhost:3001',
    'webpack/hot/only-dev-server',
  ];

  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filname: 'vendor.js'
    })
  ]);
  config.output.publicPath = 'http://localhost:3001/static/';
  config.module.loaders[0].query = {
    "env": {
      "development": {
        "presets": ["react-hmre"]
      }
    }
  };
} else {
  config.plugins = config.plugins.concat([
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filname: '[name].[chunkhash].js'
    }),
    new webpack.optimize.UglifyJsPlugin(),
    new AssetsPlugin({ path: path.join(__dirname, 'dist') })
  ]);
}

module.exports = config;

@KeKs0r
Copy link
Author

KeKs0r commented Jul 28, 2016

I solved it for my side. I figured out that the issue does not occur during bundling, but when running the bundle.

I was using it isomorphically and had node_modules excluded from the bundle. Which meant it was not processed by webpack.

@rpoitras
Copy link

rpoitras commented Aug 5, 2016

This is working for me up to the point in the docs "Using SASS Loader". Webpack 2.1.0-beta.20 does not allow sassLoader definition in module.exports.

const path = require('path')
const webpack = require('webpack')
const validate = require('webpack-validator')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const PATHS = {
  app: './app/index.js',
  html: './app/index.html',
  lib: './lib/index.js',
  src: path.join(__dirname, 'app'),
  libDir: path.join(__dirname, 'lib'),
  dist: path.join(__dirname, 'dist'),
  routes: path.join(__dirname, 'app/routes'),
  eslintrc: path.join(__dirname, './.eslintrc')
}

const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: PATHS.html,
  filename: 'index.html',
  inject: 'body'
})

module.exports = env => {
  return validate({
    entry: {
      js: PATHS.app,
      route: PATHS.routes + '/routes',
      lib: PATHS.lib,
      vendor: [
        'react', 'react-router', 'react-dom', 'babel-polyfill'
      ]
    },

    output: {
      filename: '[name].bundle.js',
      chunkFilename: '[id].bundle.js',
      path: PATHS.dist,
      publicPath: env.prod ? '/' : 'http://localhost:4000/dist/',
      pathinfo: !env.prod
    },

    context: __dirname,

    devtool: env.prod ? 'eval' : 'inline-source-map',

    bail: env.prod,

    // Enzyme config
    externals: {
      'cheerio': 'window',
      'react/lib/ExecutionEnvironment': true,
      'react/lib/ReactContext': true
    },

    module: {
      loaders: [
        {
          test: /(\.js|\.jsx)$/,
          exclude: /node_modules/,
          loaders: ['babel?presets[]=react,presets[]=es2015,presets[]=stage-0', 'eslint']
        },
        {
          test: /(\.scss|\.css)$/,
          loader: ExtractTextPlugin.extract({
            fallbackLoader: 'style-loader',
            loader: [
              'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
              'sass'
            ]
          })
        }
      ]
    },

    plugins: [
      HtmlWebpackPluginConfig,
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: Infinity,
        filename: 'vendor.bundle.js'
      }),
      new ExtractTextPlugin({
        filename: '[name].[id].style.css',
        allChunks: false
      })
    ],

    devServer: {
      contentBase: PATHS.dist,
      port: 4000,
      historyApiFallback: true
    }
  })
}

@javivelasco
Copy link
Member

This shouldn't be an issue with the next version using PostCSS :) Glad you got it working!

@Slashgear
Copy link

Slashgear commented Aug 16, 2016

Can't make it work with Webpack 2.1.0-beta.20 using Sass Loader 😢 I tried this but I have Syntaxe Error on import

       {
          test: /(\.scss|\.css)$/,
          loader: ExtractTextPlugin.extract({
            fallbackLoader: 'style-loader',
            loader: [
              'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
              'sass'
            ]
          })
        }

@rpoitras Could you add more details :)

@rpoitras
Copy link

Are your errors from Webpack or at runtime? First thing I'd ask is if you have node-sass as a devDependency?

@Slashgear
Copy link

Here is my webpack conf

const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  module: {
    loaders: [
      {
        test: /(\.js)$/,
        exclude: /node_modules/,
        loaders: ['babel?presets[]=react,presets[]=es2015,presets[]=stage-0', 'eslint']
      },
      {
        test: /(\.scss|\.css)$/,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: 'style-loader',
          loader: [
            'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
            'sass'
          ]
        })
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({
      template: conf.path.src('index.html'),
      inject: true
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      'process.env.BASE_HREF': '"/"'
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
  ],
  postcss: () => [autoprefixer],
  resolve: {
    extensions: ['', '.scss', '.css', '.js', '.json'],
    modulesDirectories: [
      'node_modules',
      path.resolve(__dirname, './node_modules')
    ]
  },
  debug: true,
  devtool: 'cheap-module-eval-source-map',
  output: {
    path: path.join(process.cwd(), conf.paths.tmp),
    filename: 'index.js'
  },
  entry: [
    'webpack/hot/dev-server',
    'webpack-hot-middleware/client',
    `./${conf.path.src('index')}`
  ]
};

And my package.json

{
  "dependencies": {
    "axios": "^0.13.1",
    "file-loader": "^0.9.0",
    "history": "^3.0.0",
    "react": "^15.0.1",
    "react-dom": "^15.0.1",
    "react-helmet": "^3.1.0",
    "react-list": "^0.7.20",
    "react-redux": "^4.4.5",
    "react-router": "^3.0.0-alpha.3",
    "react-toolbox": "^1.1.2",
    "redux": "^3.5.2",
    "redux-thunk": "^2.1.0"
  },
  "devDependencies": {
    "autoprefixer": "^6.2.2",
    "babel-core": "^6.2.0",
    "babel-eslint": "^6.0.2",
    "babel-loader": "^6.2.0",
    "babel-plugin-transform-async-to-generator": "^6.8.0",
    "babel-plugin-transform-class-properties": "^6.11.5",
    "babel-plugin-transform-object-rest-spread": "^6.8.0",
    "babel-polyfill": "^6.7.4",
    "babel-preset-es2015": "^6.2.0",
    "babel-preset-es2016": "^6.11.3",
    "babel-preset-react": "^6.1.18",
    "babel-register": "latest",
    "bluebird": "^3.4.1",
    "browser-sync": "^2.9.11",
    "browser-sync-spa": "^1.0.3",
    "css-loader": "^0.23.1",
    "del": "^2.0.2",
    "enzyme": "^2.4.1",
    "es6-shim": "^0.35.0",
    "eslint": "^2.11.0",
    "eslint-config-xo-react": "^0.7.0",
    "eslint-config-xo-space": "^0.12.0",
    "eslint-loader": "^1.3.0",
    "eslint-plugin-babel": "^3.1.0",
    "eslint-plugin-react": "^5.0.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "gulp": "gulpjs/gulp#4ed9a4a3275559c73a396eff7e1fde3824951ebb",
    "gulp-coveralls": "^0.1.4",
    "gulp-filter": "^4.0.0",
    "gulp-hub": "frankwallis/gulp-hub#d461b9c700df9010d0a8694e4af1fb96d9f38bf4",
    "gulp-sass": "^2.1.1",
    "gulp-util": "^3.0.7",
    "html-webpack-plugin": "^2.9.0",
    "inject-loader": "^2.0.1",
    "isparta-loader": "^2.0.0",
    "jasmine": "^2.4.1",
    "json-loader": "^0.5.4",
    "karma": "^0.13.14",
    "karma-coverage": "^0.5.3",
    "karma-jasmine": "^0.3.8",
    "karma-junit-reporter": "^0.4.2",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-phantomjs-shim": "^1.1.2",
    "karma-webpack": "^1.7.0",
    "lodash": "^4.14.2",
    "mkdirp-promise": "^2.0.0",
    "mz": "^2.4.0",
    "node-sass": "^3.4.2",
    "phantomjs-prebuilt": "^2.1.6",
    "postcss-loader": "^0.8.2",
    "react-addons-test-utils": "^15.0.1",
    "react-addons-update": "^15.3.0",
    "react-hot-loader": "^3.0.0-beta.1",
    "sass-loader": "^3.1.2",
    "sinon": "^2.0.0-pre.2",
    "style-loader": "^0.13.0",
    "toolbox-loader": "0.0.3",
    "webpack": "2.1.0-beta.20",
    "webpack-dev-middleware": "^1.4.0",
    "webpack-hot-middleware": "^2.6.0",
    "webpack-split-by-path": "^0.0.10"
  },
  "scripts": {
    "build": "gulp",
    "serve": "gulp serve",
    "serve:dist": "gulp serve:dist",
    "test": "gulp test",
    "test:auto": "gulp test:auto",
    "prerender": "gulp prerender",
    "coveralls": "gulp coveralls"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "browser": true,
      "jasmine": true
    },
    "rules": {
      "camelcase": 0
    },
    "extends": [
      "xo-react/space",
      "xo-space/esnext"
    ]
  }
}

@rpoitras
Copy link

@Slashgear you are probably hitting the same import error I was blocked at. I left this until the future version that @javivelasco mentioned.

@javivelasco
Copy link
Member

@Slashgear what's the exact error?

@Slashgear
Copy link

My exact error is

(function (exports, require, module, __filename, __dirname) { @import "../colors";
                                                              ^
SyntaxError: Unexpected token ILLEGAL
    at Object.exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:513:28)
    at Module._extensions..js (module.js:550:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/zenika/IdeaProjects/jcdecaux-bike-react/node_modules/babel-register/lib/node.js:156:7)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Function.Module._load (/Users/zenika/IdeaProjects/jcdecaux-bike-react/node_modules/gulp-hub/lib/load-subfile.js:26:32)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/zenika/IdeaProjects/jcdecaux-bike-react/node_modules/react-toolbox/lib/app_bar/index.js:14:14)
    at Module._compile (module.js:541:32)
    at Module._extensions..js (module.js:550:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/zenika/IdeaProjects/jcdecaux-bike-react/node_modules/babel-register/lib/node.js:156:7)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Function.Module._load (/Users/zenika/IdeaProjects/jcdecaux-bike-react/node_modules/gulp-hub/lib/load-subfile.js:26:32)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (Navbar.js:3:1)
    at Module._compile (module.js:541:32)

All my configuration with react-toolbox is on this branch

@javivelasco
Copy link
Member

Alright, I'm seeing your error comes from babel-register trying to require an scss file. This probably means you are requiring from node ES6/React straight that is not transpiled to ES5. Of course a react-toolbox component is requiring a SCSS file which is not going to work unless you configure a css modules hook or provide a way to resolve these imports from node.

I'm not familiar with your configuration so I have to dig deeper to get to know what's exactly happening. If the issue is that you can't require a CSS file from the backend try adding a https://github.com/css-modules/css-modules-require-hook. Remember to transform the SCSS into CSS too in the same config. I've pasted a configuration example in another issue (can't remember exactly which one). Sadly we have no scaffold with SSR yet but will do soon.

@Slashgear
Copy link

Can't find your configuration example either.

@javivelasco
Copy link
Member

Here you go:

var hook = require('css-modules-require-hook')
var sass = require('node-sass')
var path = require('path')

hook({
  rootDir: path.join(__dirname, '../'),
  extensions: [ '.scss' ],
  generateScopedName: process.env.NODE_ENV === 'development'
    ? '[name]__[local]___[hash:base64:5]'
    : '[hash:base64:5]',
  preprocessCss: function (data, filename) {
    return sass.renderSync({
      data: data,
      file: filename,
      includePaths: [
        path.join(__dirname, './app/components'),
        path.join(__dirname, './node_modules')
      ]
     }).css
  }
})

I get it working with that some months ago. Let me know!

@icd2k3
Copy link

icd2k3 commented Nov 4, 2016

I'm getting a similar issue after upgrading to webpack 2.1.0-beta.25 only when building bundles for production.

ERROR in ../~/react-toolbox/lib/card/theme.scss
Module build failed:
@import "../mixins";
             ^
      Invalid CSS after "module.exports": expected "{", was '= {"card":"theme__c'
...

My css is being imported as modules into React components.

react-toolbox 1.2.5
webpack 2.1.0-beta.25
extract-text-webpack-plugin 2.0.0-beta.4

Everything works fine while developing locally, but I can't seem to get past these errors for the dist bundle... any ideas?

My config

module: {
    rules: [
      {
        test: /(\.scss|\.css)$/,
        loader: extractTextWebpackPlugin.extract({
          fallbackLoader: 'style-loader',
          loader: 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass'
        })
      },
      {
        test: /(\.scss|\.css)$/,
        use: [
          {
            loader: 'postcss-loader',
            options: {
              plugins: [autoprefixer]
            }
          },
          /**
           * This is used to extend the default react-toolbox
           * theme with our own styles and preferences
           * at a global level
           */
          {
            loader: 'sass-loader',
            options: {
              data: '@import "theme/theme.scss";',
              includePaths: [paths.CLIENT]
            }
          }
        ]
      }
    ]
  }

EDIT

When I remove new webpack.LoaderOptionsPlugin({minimize: true}) from my plugins array it compiles! So it seems to be a problem with minification... still investigating.

@darklilium
Copy link

Hello, im having some problems on setting up the react toolbox lib with webpack 2.
My webpack.config is the following:

const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  context: __dirname,
  entry: {
    pageOne: './app/pageOne/index.js',
    pageTwo: './app/pageTwo/index.js',
    pageThree: './app/pageThree/index.js',
    vendor: [
      'webpack-hot-middleware/client'
    ]
  },
  output: {
    path: path.join(path.join(__dirname, 'dist'), 'js'),
    filename: '[name].js',
    libraryTarget: "amd",
    publicPath: '/'
  },
  module: {
    rules: [
       {test: /\.(js|jsx)$/,
         use: {
           loader: 'babel-loader',
           query: {
             presets: ['es2015', 'stage-0', 'react','stage-2']
           }
         },
         exclude:  /(node_modules)/
       },
       {
         test: /(\.scss|\.css)$/,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: 'style-loader',
          loader: 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass'
        })
      },
      {
        test: /(\.scss|\.css)$/,
        use: [
          {
            loader: 'postcss-loader',
            options: {
              plugins: [autoprefixer]
            }
          },
          /**
           * This is used to extend the default react-toolbox
           * theme with our own styles and preferences
           * at a global level
           */
          {
            loader: 'sass-loader',
            options: {
              data: '@import "css/index.scss";',
              includePaths: [path.resolve(__dirname, './app')]
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.scss', '.css', '.js', '.json','.webpack.js', '.web.js', '.js', '.jsx'],
    modules: [path.resolve(__dirname, './node_modules'),"node_modules"]
  },
  externals: [
      function(context, request, callback) {
          if (/^dojo/.test(request) ||
              /^dojox/.test(request) ||
              /^dijit/.test(request) ||
              /^esri/.test(request)
          ) {
              return callback(null, "amd " + request);
          }
          callback();
      }
  ],
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new ExtractTextPlugin({
      filename: '../css/style.css',
      allChunks: true
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),

    new webpack.HotModuleReplacementPlugin(),

  ],
  devServer: {
    inline: true,
    port: 443,
    host: "127.0.0.1",
    historyApiFallback: true

  },
  devtool: 'inline-source-map' //for production use: hidden-source-map
};

The error im getting is:
image

What im doing wrong?
Thanks for advice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants