1

我正在尝试使用我创建的组件库以在其他项目中重用。在其中,我使用了带有 webpack 和代码拆分的可加载组件。

但是,当导入 Next.js 项目时,会返回错误,表明您无法从该库中导入组件。

我有两个项目:

  • 项目 A = 组件库
  • 项目 B = 将导入项目 A

导入库的项目 B(项目 A):

(node:20271) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'SomeComponent' of undefined

导入库的配置(项目 A):

webpack.build.config.js

module.exports = {
...
  entry: {
    [packageName]: './src/index.js'
  },

  target: 'web',

  output: {
    chunkFilename: '[chunkhash].chunk.js',
    library: packageName,
    libraryTarget: 'commonjs2',
    globalObject: 'this'
  },

  externals: nodeExternals(),
  
  optimization: {
    minimize: true,
    usedExports: true,
    splitChunks: {
      chunks: 'all',
    },
  },

  plugins: [
    new LoadablePlugin()
  ],
...
}

src/index.js

import styled, { ServerStyleSheet, createGlobalStyle } from 'styled-components';
export * from '@components';
export * from '@style';
export { default as Icons } from '@assets/icons';
export { styled, ServerStyleSheet, createGlobalStyle };

上面,只有 @components 文件夹有 loadable-components

.babelrc


{
  "plugins": [
    "styled-components",
    [
      "@babel/plugin-proposal-pipeline-operator",
      {
        "proposal": "minimal"
      }
    ],
    [
      "@babel/plugin-proposal-optional-chaining",
      {
        "loose": false
      }
    ],
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ],
    "@loadable/babel-plugin"
  ]
}

Project B中,我只用生成的块导入这个库。

但是,无论组件是否按需加载,都会显示相同的错误。

我究竟做错了什么?有什么建议吗?

谢谢!

4

0 回答 0