【问题标题】:Is there a way to use splitChunksPlugin in Webpack 4 to manually control which modules get placed into which output bundles?有没有办法在 Webpack 4 中使用 splitChunksPlugin 来手动控制哪些模块被放置到哪些输出包中?
【发布时间】:2019-04-15 21:09:49
【问题描述】:

我处于一种独特的情况,我需要将我的捆绑包分成单独的文件,但我没有奢侈的文件总数或这些文件的名称随着时间的推移随着应用程序的变化而变化增长并安装新的依赖项等。

以下配置是错误的,但我认为它最能说明我尝试要完成的工作。我已经阅读了所有文档,但似乎找不到与这些内容相关的任何内容。

optimization: {
  splitChunks: {
    react: {
      test: /node_modules\/react/
    },
    vendor: {
      test: /node_modules\/(?!react)/
    },
    svgIcons: {
      test: /src\/js\/components\/icons/
    },
  }
}

我们的目的是最终得到以下 4 个捆绑包:

react.bundle.js - Contains all react-related dependencies
vendor.bundle.js - Contains all other vendor files from node modules
svgIcons.bundle.js - Contains a group of app component files that match my test
bundle.js - The default bundle containing everything else.

有没有办法做到这一点?

【问题讨论】:

    标签: webpack webpack-4 webpack-splitchunks


    【解决方案1】:

    经过更多的挖掘,我最终弄明白了。本质上,这就是您所需要的:

    首先,在output对象中...

    output: {
      filename: "[name].js"
    }
    

    您需要 [name] 变量,否则您的包将无法获取正确的名称。

    接下来,在optimization 对象中...

    optimization: {
      splitChunks: {
        cacheGroups: {
          react: {
            chunks: 'initial',
            name: 'react',
            test: /node_modules\/react/,
            enforce: true,
          },
          vendor: {
            chunks: 'initial',
            name: 'vendor',
            test: /node_modules\/(?!react)/,
            enforce: true,
          },
          icons: {
            chunks: 'initial',
            name: 'icons',
            test: /src\/js\/components\/icons/,
            enforce: true,
          },
        },
      },
    },
    

    产生以下捆绑包:

    react.js
    vendor.js
    icons.js
    bundle.js
    

    【讨论】:

    • 另请注意,您可以为“测试”字段值传递函数
    • 您也可以通过文件路径进行测试:test: path.resolve(process.cwd(), 'path', 'to', 'module',
    猜你喜欢
    • 2012-10-19
    • 2018-06-09
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2012-11-03
    • 2012-07-18
    相关资源
    最近更新 更多