简体   繁体   中英

How to properly Webpack library export?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM