I'm trying to build a project with Webpack 5.74.0 (after installing it globally):
webpack --config src/webpack.config.js
My src/webpack.config.js file uses import syntax, eg:
import ReactRefreshPlugin from '@pmmmwh/react-refresh-webpack-plugin';
But that should be fine because I have:
"type": "module"
in the project's package.json. However, despite that, when I run Webpack I get:
[webpack-cli] Failed to load '/home/me/project/src/webpack.config.js' config
[webpack-cli] /home/me/project/src/webpack.config.js:1
import ReactRefreshPlugin from '@pmmmwh/react-refresh-webpack-plugin';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at WebpackCLI.tryRequireThenImport (/home/me/project/node_modules/webpack-cli/lib/webpack-cli.js:204:22)
at loadConfigByPath (/home/me/project/node_modules/webpack-cli/lib/webpack-cli.js:1404:38)
I understand that I can use loaders to enable import syntax in the project I'm building ... but how can I fix Webpack to read the config file, if it ignores my package.json?
EDIT: I found a workaround: if I rename webpack.config.js => webpack.config.mjs (ie. I force it to recognize the file as an ES Module file) everything works.
But, it still doesn't answer why Webpack ignores "type": "module" in my package.json, so I'm leaving the question open in hopes of understanding that.