无法从webpack bundle

时间:2018-06-02 15:25:25

标签: javascript node.js webpack ecmascript-6

我有2个本地项目。其中一个是第二个的UI库,但它们必须是分开的。第二个项目是应该从单个文件加载UI库的应用程序 - UI库生成的包 - index.js

我使用webpack 4生产配置完成了UI库,如下所示:

const path = require('path')

const webpackConfig = {
  entry: {
    index: './src/styleguide/main.js',
  },
  devtool: 'source-map',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      { test: /\.js/, use: 'babel-loader' },
    ],
  },
  mode: 'production',
}

module.exports = webpackConfig;

要弄清楚,让我们使用以下作为我的index.js

export default function Text () { return <p>Hello world</p> }

这会产生一个“dist / index.js”文件,这也是package.json

中的入口点

在另一个需要使用UI库的项目中,我只想做import UI from '../ui/dist/index.js'

但是UI要么是空对象{}要么是未定义的,要么抛出未捕获的错误:缩小的反应错误#200;访问https://reactjs.org/docs/error-decoder.html?invariant=200以获取完整的消息,或使用非缩小的开发环境获取完整错误和其他有用的警告。

我尝试过设置librarylibraryTarget,将我的脚本简化为一个没有依赖关系的内容,我对我所缺少的内容感到非常焦虑。我会感激以获得任何帮助!

1 个答案:

答案 0 :(得分:0)

在UI库中将output.libraryTarget设置为commonjs2可以解决您的问题。

除此之外,您可能还希望在UI库中设置反应为peerDependency并配置webpack:

externals: {      
    // Don't bundle react      
    react: {          
        commonjs: "react",          
        commonjs2: "react",          
        amd: "React",          
        root: "React"      
    }  
},

这可能导致更小的捆绑。