I am starting to familiarize with javascript development. I want to use modern syntax and use webpack. But I still quite don't understand how this works.
When I run npx webpack --config webpack.config.babel.js
I get this error:
Cannot use import statement outside a module
This is my minimal reproducible example:
package.json
{
"name": "mre2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.10.3",
"@babel/preset-env": "^7.10.3",
"path": "^0.12.7",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
}
}
config.babel.js
module.exports = {
"presets": ["@babel/preset-env"]
}
index.js
console.log('hello world')
webpack.config.babel.js
import path from 'path';
export default {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
resolve: {
extensions: [
'.js'
]
}
};
When I add "type": "module"
to my package.json, I get this other error
Must use import to load ES Module: /home/liliam/Alejo/mre2/webpack.babel.config.js
require() of ES modules is not supported.
require() of /home/liliam/Alejo/mre2/webpack.babel.config.js from /home/liliam/Alejo/mre2/node_modules/webpack-cli/bin/utils/convert-argv.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename webpack.babel.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/liliam/Alejo/mre2/package.json.
How can I solve this?