First real foray into using webpack, and I'm trying to create a reusable library. I can't figure out how to properly export my library classes. Here's a general rundown of what I'm currently doing, and how I'm trying to use what's been built.
I have an entry point like so:
import ClassA from './classA';
import ClassB from './classB';
export {ClassA, ClassB};
That I would like to use the built library to import my classes when needed in my application:
import {ClassA} from './libs/library.js'; // currently using chrome flags for testing
But I can not figure out the right 'output' configuration for my webpack build. I'm using babel-env with a .babelrc like:
{
"presets": [[
"env", {
"targets": {
"browsers": "last 2 versions"
}
}
]]
}
and a webpack config like:
const path = require('path');
export default () => ({
entry: __dirname + '/src/index.js',
output: {
path: path.resolve(__dirname, './libs'),
filename: 'library.js',
libraryTarget: 'umd',
library: ''
},
externals: {},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "eslint-loader"
}
}]
},
resolve: {
modules: [path.resolve('./node_modules'), path.resolve('./src')],
extensions: ['.json', '.js']
}
});
But, when trying to use my classes, via the import shown earlier, I get an error:
Uncaught SyntaxError: The requested module does not provide an export named 'ClassA'
Anyone have an idea what I'm doing wrong? I'm sure I'm just missing the right configuration of webpack options, but hours of Google have not helped.
Webpack supports the following module types natively: ECMAScript modules. CommonJS modules.
Tree shaking is a term commonly used within a JavaScript context to describe the removal of dead code. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.
There seems to be a long-standing feature request in Webpack to resolve this.
In the meantime, you may be able to do a simple import './classA'
, which should add the variables to the global scope (this is the default behaviour of the libraryTarget: 'umd'
option)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With