2

我创建了模块 A,它是我的 React 应用程序的组件库。我计划在模块 B 上使用它,这是我的实际 React 应用程序。

我有一个 index.js ,我通过以下方式使用可加载组件从模块 A 导出我的组件

import loadable from '@loadable/component'

export const Theme = loadable(() => import('./Theme'))
export const OtherComponent = loadable(() => import('./OtherComponent'))
export const OtherComponent2 = loadable(() => import('./OtherComponent2'))

因此,我使用以下 webpack 配置构建模块 A 并将其部署到 npm

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const TerserPlugin = require("terser-webpack-plugin")
const LoadablePlugin = require('@loadable/webpack-plugin')

module.exports = {
  mode: 'production',
  optimization: {
    usedExports: true,
    minimize: true,
    concatenateModules: false,
    minimizer: [new TerserPlugin({
      terserOptions: {
        keep_fnames: true
      }
    })],
    
  },
  entry: {
    main: './src/components/index.js',
  },
  output: {
    publicPath: '/',
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    library: "myComponentLibrary", 
    libraryTarget: "umd",
    globalObject: "this"
  },
  externals: {
    react: {
      root: 'React',
      commonjs: 'react',
      commonjs2: 'react',
      amd: 'react',
    },
  },
  plugins: [new CleanWebpackPlugin(), new LoadablePlugin()],
  module: {
    rules: [
     {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
            options: {
              cacheDirectory: true
            }
          }
        ],
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        type: 'asset/inline'
      },
    ]
  }
}


我希望当我在模块 B 上 npm install module A 时能够导入和呈现我的组件,但我得到了以下错误。

loadable-components: 无法异步加载组件 { fileName: undefined, chunkName: undefined, error: 'Loading chunk 2661 failed.\n(error: 2661.js)' }

请提供一些有关如何解决此问题的指导

4

1 回答 1

1

如果一切在开发中运行良好,但在生产中却没有,并且您遇到此错误,请将其添加<base href="/"/>到 index.html 的头部:

<!DOCTYPE html>
<html>
    <head>
        <base href="/"/>
        <meta charset="utf-8" />
        <title>Foo project</title>
    </head>

    <body>
        <div id="app"></div>
        <!-- built files will be auto injected -->
    </body>
</html>

现在,我认为一切都运作良好。这个问题是因为html5路由的,你可以搜索一下。

于 2021-12-27T18:25:40.740 回答