The below webpack configuration (in ES6) and package.json work. Essentially the package.json needs to contain "type":"module" indicating the target is ES6. The webpack configuration then needs to export an javascript object whose properties are configuration keys and the values as appropriate. Below is an example:
"use strict"
import webpack from 'webpack';
export default {
mode: "development",
entry: ["./src/lib-junk.jsx"],
experiments: {outputModule: true},
output: {
filename: "lib-junk-dist.js",
clean: true,
library: {type: "module"}
},
devtool: "source-map",
module: {
rules:[
{
test: /\.(js|mjs|jsx)?$/,
loader: 'babel-loader',
options:{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
},
exclude: [/node_modules/]
}
]
},
externalsType: 'module',
externals: {
'react': 'react',
'react-dom/client': 'react-dom/client',
},
plugins: []
}
The equivalent CommonJS is as below:
"use strict"
const webpack = require('webpack');
module.exports = {
mode: "development",
entry: ["./src/lib-junk.jsx"],
//Refer: https://mcmap.net/q/111078/-output-an-es-module-using-webpack
experiments: {outputModule: true},
output: {
filename: "lib-junk-dist.js",
clean: true,
//Refer: https://mcmap.net/q/111078/-output-an-es-module-using-webpack
library: {type: "module"}
},
devtool: "source-map",
module: {
rules:[
{
test: /\.(js|mjs|jsx)?$/,
loader: 'babel-loader',
//options: babelrc,
options:{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
},
exclude: [/node_modules/],
}
]
},
externalsType: 'module',
externals: {
'react': 'react',
'react-dom/client': 'react-dom/client',
},
plugins: []
}
The dependencies for the above in package.json is as below
"files":["components/*","*.mjs"],
"main":"index.js",
"type":"module", //This is essential for ES6
"scripts": {
"build": "webpack --config build/webpack.config.dev.js"
},
"dependencies": {
},
"peerDependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies":{
"@babel/core": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.1",
"webpack": "^5.1.4",
"webpack-cli": "^5.1.4",
"url-loader":"^4.1.1",
"file-loader": "^6.0.0"
}
NOTE: In my case I am using Babel to transpile .jsx files only, it is not required for webpack to use this config, far I could figure.
require
. It seems overkill to installbabel
JUST for the webpack config file! – Dionnadionne