Reputation: 298
I have a problem with configurations of Babel 7, Webpack 4 and Jest. While I'm running tests I'm getting following error:
SyntaxError: Cannot use import statement outside a module
package.json
"@babel/core": "^7.7.5",
"@babel/highlight": "^7.8.3",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/preset-env": "^7.8.4",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^7.1.5",
"@babel/plugin-transform-runtime": "^7.7.4",
"@babel/preset-react": "^7.7.4",
"@babel/runtime": "^7.8.4",
"babel-jest": "^24.9.0",
"jest-watch-typeahead": "^0.4.2",
"vue-jest": "^3.0.5",
"jest": "^24.9.0",
"jest-serializer-vue": "^2.0.2",
"jest-transform-stub": "^2.0.0",
webpack.config.js
entry: {
app: ["./src/index.js"]
},
output: {
path: path.resolve('../', 'static/js/'),
filename: "[name].js",
publicPath: '/static/js/',
chunkFilename: '[name].chunk.js'
},
.babelrc - I assumed that the problem is with module: false but if I dont include that, webpack doesnt chunk my files.
{
"presets": [
["@babel/preset-env", {"modules": false}, "jest" ]
],
"plugins": [
"@babel/plugin-syntax-dynamic-import"
],
"env": {
"test": {
"plugins": ["@babel/plugin-transform-runtime"],
}
}
}
When I removed module: false tests were running, are there any chances to dont include module: false into tests?
Upvotes: 6
Views: 14585
Reputation: 2047
Since [email protected]
, it is not needed to transpile code to support esm in tests anymore as it supports it natively. You can find here, how to achieve that as it is not documented yet.
Upvotes: 0
Reputation: 27237
From the Babel Options documentation:
Note: env[envKey] options will be merged on top of the options specified in the root object.
So you can apply modules: "auto"
during testing by redeclaring the plugin in the env.test
object:
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
},
"jest"
]
],
"plugins": [
"@babel/plugin-syntax-dynamic-import"
],
"env": {
"test": {
"presets": [
[
"@babel/preset-env",
{
"modules": "auto"
},
"jest"
]
],
"plugins": [
"@babel/plugin-transform-runtime"
]
}
}
}
Upvotes: 4
Reputation: 4318
import
statements are only permitted in ES modules. Your tests are running in Node which uses commonjs modules.
Try adding "type": "module"
to your package.json
file
Also check the version of Node you are running, you can find more on this in the node docs https://nodejs.org/api/esm.html#esm_ecmascript_modules
Upvotes: 0