Is it possible to use Webpack 5 to build an ES module bundle (with a default export), and then consume (import) that bundle in a Node.js ES module?
- Here's a live demo of the following files.
I've got the following files:
|- webpack.config.js
|- package.json
|- /src
|- index.js
index.js
function util() {
return "I'm a util!";
}
export default util;
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
experiments: {
outputModule: true,
},
};
package.json
{
"name": "exporter",
"version": "1.0.0",
"module": "dist/index.js",
"scripts": {
"build": "webpack"
}
}
After running npm run build
, we get:
|- webpack.config.js
|- package.json
|- /src
|- index.js
|- /dist
|- bundle.js
Great, now I want to just create some "demo" file importer.js
which would import util
and use it. For convenience, I'll create it on the same folder:
|- importer.js
|- webpack.config.js
|- package.json
|- /src
|- index.js
|- /dist
|- bundle.js
importer.js
import util from './dist/bundle.js';
console.log(util());
Now I run node importer.js
, and I get this (expected) error:
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
[...]
SyntaxError: Cannot use import statement outside a module
Ok then, let's add that "type": "module"
to package.json
:
package.json
{
"name": "exporter",
"version": "1.0.0",
"module": "dist/index.js",
"scripts": {
"build": "webpack"
},
"type": "module"
}
Now, trying again node importer.js
get us another error:
SyntaxError: The requested module './dist/bundle.js' does not provide an export named 'default'
What's more, when trying to re-run npm run build
, we get yet another error:
[webpack-cli] Failed to load 'path\to\webpack.config.js' config
[webpack-cli] ReferenceError: require is not defined
- Note: Webpack 5 and ESM might be considered as somewhat related, but really it isn't, as it wants to use
webpack.config.js
itself as an ES module.
How can I make it work?
package.json
. – Aeolotropicwebpack@^5.51.1
andwebpack-cli@^4.8.0
I end up with an emptybundle.js
file when I attempt to build. – Aeolotropic