Webpack根据chunk加载不同的模块

10

根据一些上下文信息,有可能让webpack加载另一个模块吗?

例如,我有两个版本的React应用程序:桌面版和移动版

在我的index.js中,我决定要加载哪个应用程序:

if (isMobile()) {
   loadMobile().then(({default: App}) => render(App))
}

现在我想要重用一些模块,但有些我想要覆盖它们。所以默认情况下应该加载 index.js ,但如果上下文是 isMobile 并且在 index.js 旁边存在一个 mobile.js 文件,则应加载 mobile 变量

components/
  Button/
    index.js
    mobile.js

在移动端环境下,webpack 应该加载 mobile.js 而不是 index.js

我找不到任何可以用来解决这个问题的东西,有什么想法吗?


PS:我已经在 GitHub 上创建了一个问题,它更好地展示了我的问题和我想要实现的目标:

https://github.com/webpack/enhanced-resolve/issues/180

3个回答

5
您可以使用动态加载函数和动态导入语法来解决这个问题。
  1. Install Babel plugin plugin-syntax-dynamic-import:

    npm install --save-dev @babel/plugin-syntax-dynamic-import
    

    and use it in .babelrc

    {
      "plugins": ["@babel/plugin-syntax-dynamic-import"]
    }
    
  2. You need to create a component called load with the following codes:

        export default const load = (platform="index") => componentName => 
        import(`components/${componentName}/${platform}.js`);
    
  3. Then use dynamic import with loading function like the following code:

        const { Button } = await import("components/Loader.jsx").then(load => {
          load(${platform})(${componentName})
        })
    
这些文章可能会对您有所帮助:

感谢您的努力写下这篇文章,但它并没有回答我的原始问题。这种方法的问题在于所有模块都是动态加载的,因此必须使用 Promises。我的原始问题已经使用了动态加载方法,我只是想找到一种将 mobile.js 文件包含到 mobile.bundle.js 中,而将默认(index.js)文件包含到 desktop.bundle.js 中的方法。 - webdeb
好的,那这篇文章怎么样:https://remarkablemark.org/blog/2017/02/25/webpack-ignore-module/。这篇文章可能会解决这个问题。你将有两个构建版本,在每个版本中,你都可以删除不必要的部分。 - tunaayberk
这正是我想要避免的。 - webdeb

0

我猜你必须创建两个构建版本:一个带有默认的resolve.mainFiles,另一个则是

resolve: {
    mainFiles: ['mobile', 'index']
}

您需要决定在您的HTML中加载哪个包。或者创建两个不同的HTML文件,并将isMobile逻辑移动到Web服务器配置中,以便它决定返回哪个HTML给用户。

两个构建之间可能有一些相同的块。但很可能最终会得到两个不同的应用程序。您可以使用DllPlugin来减少两个应用程序之间的构建代码重复。


0

你可以通过两种不同的方式来实现这个目标。

  1. 创建两个入口点,一个用于移动端,一个用于桌面端,这样webpack会生成两个包。你可以从html中仅加载所需的包。
  2. 如果你在loadMobile()require/import移动端代码,webpack会自动将代码拆分成两个包。只有在需要时才会加载移动端包。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接