【问题标题】:loadable-components: failed to asynchronously load componentloadable-components:无法异步加载组件
【发布时间】:2021-12-06 03:26:40
【问题描述】:

我创建了模块 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)' }

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

【问题讨论】:

  • 这个有什么更新吗?

标签: javascript reactjs webpack dynamic-import loadable-component


【解决方案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路由的问题,可以搜索一下。

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 2019-09-28
    • 2019-02-13
    • 2020-01-09
    • 2019-06-18
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多