I'm trying to create a library that could be used using one of following method:
import MyLibrary from 'mylibrary';
const instance = new Mylibrary();
and
<script src="mylibrary.js"></script>
<script>
var instance = new MyLibrary();
</script>
To do this I have a very simple index.js which contains:
class MyLibrary {
hello() {
console.log('hello');
}
}
export default MyLibrary;
And I installed webpack / webpack-cli / babel-core / babel-cli / babel-preset-env and babel-loader via npm. Then I created a webpack.config.js file with the following content:
const path = require('path')
module.exports = {
entry: {
MyLibrary: './src/index.js'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].js',
library: '[name]',
libraryExport: 'default',
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
};
When I test it :
-
<script src="MyLibrary.js"></script> <script> var instance = new MyLibrary(); console.log(instance.hello()); </script>
Is working
-
import MyLibrary from './MyLibrary.js'; console.log(MyLibrary);
I get the following error:
Uncaught SyntaxError: The requested module './MyLibrary.js' does not provide an export named 'default'
If I remove the rule libraryExport: 'default'
from my webpack config then:
- I have to call my library like this:
var instance = new MyLibrary.default();
- I still having the same issue
Uncaught SyntaxError: The requested module './MyLibrary.js' does not provide an export named 'default'
How can I do to get this work ?