可加载组件:异步加载组件失败

2024-04-20

我创建了模块 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 安装模块 A 时能够导入和渲染我的组件,但我收到以下错误。

loadable-components: 异步加载组件失败 { fileName: undefined, chunkName: undefined, error: '加载块 2661 失败。\n(error: 2661.js)' }

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


如果开发时一切正常,但生产则不然,并且您遇到此错误,请添加此<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路由的问题,你可以搜索一下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

可加载组件:异步加载组件失败 的相关文章

随机推荐