【问题标题】:Expose components so that they can be dynamically imported in app暴露组件,以便它们可以在应用程序中动态导入
【发布时间】:2018-03-18 10:02:55
【问题描述】:

我正在构建一个要在 React 应用程序中导入的组件库。我想公开这些组件,以便它们可以在应用程序中动态导入。

我尝试了什么:

lib > index.js

export const Component1 = import(/* webpackChunkName: "components/Component1" */ './components/Component1')
export const Component2 = import(/* webpackChunkName: "components/Component2" */ './components/Component2')

lib > webpack.config.js

entry: path.resolve('src/index.js'),
output: {
    path: path.resolve('build'),
    filename: 'index.js',
    chunkFilename: '[name].js',
    library: 'lib',
    libraryTarget: 'umd'
},

构建结果

80.13 KB  build/index.js
69.68 KB  build/components/Component1.js
12.4 KB   build/components/Component2.js

我想要达到的目标:

应用程序> index.js

import('lib/components/Component1').then(module => {
    console.log(module) // Empty object so far
})

我想如何导出组件以便它们一一可用?还是有别的办法?

【问题讨论】:

  • 从您的构建结果输出看来,这正是您实现的目标?我错过了什么?您没有包含两个组件的components 目录吗?您可能还需要在配置中设置 libraryExport: default 选项。 webpack.js.org/configuration/output/#output-libraryexport
  • 我在输出中有组件,但是当我想在应用程序中检索它们时它们不可用。不过我会尝试设置 libraryExport 选项。

标签: reactjs webpack code-splitting


【解决方案1】:

最后我通过使用此处定义的配置成功实现了我的意思:https://github.com/webpack/webpack/tree/master/examples/multi-part-library

我不再异步导入组件,而是在 webpack 配置中设置不同的条目。

【讨论】:

    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多