How can I use ES6 in webpack.config.js?

Solution 1:

Try naming your config as webpack.config.babel.js. You should have babel-register included in the project. Example at react-router-bootstrap.

Webpack relies on interpret internally to make this work.

Solution 2:

As an alternative to what @bebraw suggests, you can create a JavaScript automation script with ES6+ syntax:

// tools/bundle.js

import webpack from 'webpack';
import webpackConfig from './webpack.config.js'; // <-- Contains ES6+

const bundler = webpack(webpackConfig);

bundler.run(...);

And execute it with babel:

$ babel-node tools/bundle

P.S.: Calling webpack via JavaScript API might be a better approach (than by calling it via a command line) when you need to implement more complex build steps. E.g. after server-side bundle is ready, startup Node.js app server, and right after Node.js server is started, launch BrowserSync dev server.

See also:

  • React Starter Kit (package.json/scripts, tools/bundle.js, tools/webpack.config.js)
  • React Static Boilerplate (run.js, webpack.config.js, node run)
  • You might not need Gulp.js

Solution 3:

Another approach is to have a npm script like this: "webpack": "babel-node ./node_modules/webpack/bin/webpack", and run it like so: npm run webpack.

Solution 4:

I had a problem getting @Juho's solution running with Webpack 2. The Webpack migration docs suggest you to turn of babel module parsing:

It is important to note that you will want to tell Babel to not parse these module symbols so webpack can use them. You can do this by setting the following in your .babelrc or babel-loader options.

.babelrc:

{
    "presets": [
         ["es2015", { "modules": false }]
    ]
}

Sadly, this conflicts with the automatic babel register functionality. Removing

{ "modules": false }

from the babel config got things running again. However, this would result in breaking tree-shaking, so a complete solution would involve overwriting the presets in the loader options:

module: {
    rules: [
        {
            test: /\.js$/,
            include: path.resolve('src'),
            loader: 'babel-loader',
            options: {
                babelrc: false,
                presets: [['env', {modules: false}]]
            }
        }
    ]
}

Edit, 13th Nov 2017; updated webpack config snippet to Webpack 3 (thanks to @x-yuri). Old, Webpack 2 snippet:

{
    test: /\.js$/,
    exclude: ['node_modules'],
    loader: 'babel',
    query: {
        babelrc: false,
        presets: [
            ['es2015', { modules: false }],
        ],
    },
},