首页 > 解决方案 > Webpack-4 如何使用多个条目和 SSR 制作独立和有条件的 splitChunks

问题描述

我想从某个捆绑包中制作多个块,并由服务器有条件地使用它。html中是否放置某些脚本的逻辑由另一个应用程序控制,这不是问题。我尝试了可加载组件,但对我不起作用,因为他生成了糟糕的树依赖。

 export const entry = {
  testAB: testABPath,
  clients: clientsPath,
  styles: stylesPath,
  amp: ampPath,
}

然后,我有:

export const optimization = {
  splitChunks: {
    chunks: 'async',
    cacheGroups: {
      vendor: {
        test(mod) { return checkTest(/[\\/]node_modules[\\/]/, mod)},
        name: 'vendor',
        reuseExistingChunk: true,
        filename: '[name].bundle.js',
        priority: -10,
        chunks: 'all'
      },
      headerA: {
        test: new Regex('/app/src/modules/header/headerA'),
        name: 'header-module-A',
        reuseExistingChunk: true,
        filename: '[name].bundle.js',
        priority: -10,
        chunks: 'all'
      },
      headerB: {
        test: new Regex('/app/src/modules/header/headerB'),
        name: 'header-module-B',
        reuseExistingChunk: true,
        filename: '[name].bundle.js',
        priority: -10,
        chunks: 'all'
      }
    }
  }
}

这会生成一个没有 Header 模块代码的 clients.js,以及 header-module-A 和 header-module-B 文件,很酷。

方案 1

我在一个页面中调用clients.js、header-module-A 和header-module-B。一切都很好。

方案 2

我调用clients.js,header-module-A,但在某个页面中没有header-module-B。clients.js 文件不起作用,因为他的 header-module-b 有一个依赖项(该文件使用 checkDeferredModules 函数检查所有模块)。

此时,我找到了带有 runtimeChunk: 'single' 选项的解决方案https://github.com/webpack/webpack/issues/9629 ,这些会生成一个新的运行时文件。我此时的配置是这样的:

export const optimization = {
runtimeChunk: 'single',
  splitChunks: {
    chunks: 'async',
    cacheGroups: {
      vendor: {
        test(mod) { return checkTest(/[\\/]node_modules[\\/]/, mod)},
        name: 'vendor',
        reuseExistingChunk: true,
        filename: '[name].bundle.js',
        priority: -10,
        chunks: 'all'
      },
      ...getOtherChunks,
    }
  }
}

我已将 runtime.js 文件放在页眉,将其余脚本放在页脚,但不起作用。

新场景1

我在一个页面中调用clients.js、header-module-A 和header-module-B。标题不起作用。

新场景2

我调用clients.js,header-module-A,但在某个页面中没有header-module-B。标题不起作用。

我在做什么错?

标签: javascriptwebpackvendorwebpack-splitchunkssplitchunksplugin

解决方案


推荐阅读