I'm trying to migrate an older library to use ES6 imports/exports (eg. replacing const SomeClass = require('./SomeClass')
to import SomeClass from './SomeClass'
).
The problem is that when I try to use the generated umd lib package, a Module
instance is returned instead of the library itself.
<script src="lib.min.js"></script>
<script>
var lib = new Lib();
// Should be Lib instance, instead receive the following:
Module { {default: ƒ, __esModule: true, Symbol(Symbol.toStringTag): "Module" }
<script>
Here are my package.json devDependencies:
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"babel-loader": "^8.0.5",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1"
Here is my webpack config:
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
libraryTarget: 'umd',
library: 'Lib',
filename: 'lib.min.js',
path: (__dirname + '/dist')
},
module: {
rules: [
{
test: /\.js$/,
include: [__dirname + '/src'],
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
]
}
};
And here is a sample code from the library I'm working on:
// /src/SomeClass.js
export default class SomeClass {...};
// /src/index.js
import SomeClass from './SomeClass';
export default SomeClass;
Probably I messed up something with the webpack/babel-loader configuration but can't find what exactly I'm not doing correct.
After following various github issue threads, it seems that this is intended behavior for Babel6+, since they dropped export default modules.export (https://github.com/babel/babel/issues/2212).
If you need to add it (eg. to prevent calling Lib.default
), there is a babel-plugin-add-module-exports
that should fix it. My updated babel loader configuration looks like this:
presets: [['@babel/env', { 'modules': 'umd' }]],
plugins: ['add-module-exports']