How can I use ES6 in webpack.config.js?
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.
This is what worked for me using webpack 4:
In package.json
:
"scripts": {
"dev": "cross-env APP_ENV=dev webpack-serve --require @babel/register"
},
"devDependencies": {
"@babel/core": "^7.0.0-rc.1",
"@babel/register": "^7.0.0-rc.1",
"@babel/preset-env": "^7.0.0-rc.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2"
},
"babel": {
"presets": [
["@babel/preset-env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-es2015-modules-commonjs"
]
}
You can clearly see how each dependency is used, so no surprises there.
Note I am using webpack-serve
--require, but if you want to use the webpack
command instead, replace it with webpack --config-register
. In either case, @babel/register
is needed to make this work.
And that's it!
yarn dev
And you are able to use es6
in the config!
For webpack-dev-server
, use the --config-register
option which is the same as with the webpack
command
NOTE:
NO need to rename the config file to webpack.config.babel.js
(as suggested by the accepted answer). webpack.config.js
will work just fine.
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
.
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