Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  40] [ 2]  / answers: 1 / hits: 26325  / 7 Years ago, sun, january 22, 2017, 12:00:00

I have a React project which uses Webpack as the module bundler, and babel-loader to transform it into ES5, using the following settings:



module: {
rules: [
{
test: /.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: babel-loader
}
]
}
]
},


The options are set in a stand-alone .babelrc file.



Babel 6.13.0 supports ECMAScript modules, which means ECMAScript modules doesn't need to be transformed into CommonJS modules first. To get this behaviour, the documentation says that we should use this setting in our .babelrc.



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


However, when I try to run Webpack using this setting, it comes back with the error:



$ ./node_modules/.bin/webpack
/home/d4nyll/foo/bar/webpack.config.babel.js:1
(function (exports, require, module, __filename, __dirname) { import webpack from 'webpack';
^^^^^^
SyntaxError: Unexpected token import


I'm guessing this is because babel-loader doesn't act on webpack.config.babel.js, and so it's not recognising the import keyword. The error does not appear when { modules: false } is removed, but I want that functionality. How can I get Babel to recognise webpack.config.babel.js?


More From » webpack

 Answers
112

The following worked for me.



Set .babelrc to the following:



{
presets: [es2015]
}


The .babelrc settings would apply to the webpack.config.babel.js file.



Next, change the Webpack configuration to include the options you want applied to your application code.



module: {
rules: [
{
test: /.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: babel-loader,
options: {
presets: [[es2015, {modules: false}], react]
}
}
]
}
]
},

[#59252] Friday, January 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;