webpack splitChunks:如何将依赖项合并到命名块中?

时间:2018-10-07 18:55:02

标签: javascript webpack

假设您在下面有一个项目:

package.json

{
  "name": "webpack-test-repo",
  "main": "index.js",
  "dependencies": {
    "define-properties": "^1.1.3"
  },
  "devDependencies": {
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.2"
  }
}

index.js

// dynamically load the 'define-properties' module.
import('define-properties');

webpack.config.js

module.exports = {
    mode: 'production',
    entry: './index.js',
    output: {
        chunkFilename: '[name].js',
    },
    optimization: {
        splitChunks: {
            minSize: 0, // <- just to demonstrate the situation with small packages
            cacheGroups: {
                defineProperties: {
                    test: /node_modules\/define-properties\//,
                    name: 'define-properties',
                },
            },
        },
    },
};

请注意,导入的模块 define-properties 具有单个依赖项 object-keys

我在webpack.config.js中配置了splitChunks,以便将define-properties的内容拆分为define-properties.js

运行webpack的结果如下:

$ npx webpack
Hash: 7d9500fb0e6bfd1e32d1
Version: webpack 4.20.2
Time: 127ms
Built at: 2018-10-08 03:25:47
               Asset       Size  Chunks             Chunk Names
             main.js   2.05 KiB       0  [emitted]  main
define-properties.js  754 bytes       1  [emitted]  define-properties
                2.js   2.08 KiB       2  [emitted]  
Entrypoint main = main.js
[0] ./index.js 81 bytes {0} [built]
    + 3 hidden modules

这里我们得到三个输出文件:main.js用于index.js的内容,define-properties.js用于define-properties模块,以及2.js用于{{1 }}模块。

问题

我希望将object-keys的块合并到object-keys中,因为它仅由define-properties使用。

换句话说,我想仅通过指定父模块将define-properties及其依赖项打包到一个命名的块中。

尽管define-properties适用于本示例,但我不想列出test: /node_modules\/(?:define-properties|object-keys)\//的所有(可能很多)依赖项。

如何配置webpack来实现它?

0 个答案:

没有答案