簡體   English   中英

無法從Webpack捆綁包導入ES6模塊

[英]Can't import ES6 modules from webpack bundle

我有2個本地項目。 其中一個是第二個的UI庫,但是必須將它們分開。 第二個項目是一個應從單個文件加載UI庫的應用程序index.js庫生成的捆綁軟件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可能是空對象{}或未定義,或者拋出Uncaught錯誤:最小化React錯誤#200; 請訪問https://reactjs.org/docs/error-decoder.html?invariant=200獲取完整消息,或使用非最小化的dev環境獲取完整錯誤和其他有用的警告。


我嘗試設置librarylibraryTarget ,將我的腳本簡化為一個沒有依賴項的襯里,而我對所缺少的內容感到非常焦慮。 我將不勝感激

在UI庫commonjs2 output.libraryTarget設置為commonjs2應該可以解決您的問題。

除此之外,你可能還需要設置為反應peerDependency在UI libiary和配置的WebPack:

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

這可以導致捆束更小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM