简体   繁体   English

如何正确地将Webpack库导出?

[英]How to properly Webpack library export?

First real foray into using webpack, and I'm trying to create a reusable library. 第一次尝试使用webpack,我正在尝试创建一个可重用的库。 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. 但是我无法为我的webpack构建找出正确的“输出”配置。 I'm using babel-env with a .babelrc like: 我正在使用带有.babelrc的babel-env:

{
  "presets": [[
    "env", {
      "targets": {
        "browsers": "last 2 versions"
      }
    }
  ]]
}

and a webpack config like: 和webpack配置像:

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' 未捕获的SyntaxError:请求的模块不提供名为“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选项配置,但谷歌的数小时没有帮助。

There seems to be a long-standing feature request in Webpack to resolve this. 在Webpack中似乎有一个长期的功能请求来解决这个问题。

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) 在此期间,您可以执行一个简单的import './classA' ,它应该将变量添加到全局范围(这是libraryTarget: 'umd'的默认行为libraryTarget: 'umd'选项)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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