优化(optimization)

从 webpack 4 开始,会根据你选择的 mode 来执行不同的优化,不过所有的优化还是可以手动配置和重写。

optimization.minimize

boolean

告知 webpack 使用 TerserPlugin 压缩 bundle。

production 模式下,这里默认是 true

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. minimize: false
  5. }
  6. };

了解 mode 工作机制。

optimization.minimizer

[<plugin>] and or [function (compiler)]

允许你通过提供一个或多个定制过的 TerserPlugin 实例,覆盖默认压缩工具(minimizer)。

webpack.config.js

  1. const TerserPlugin = require('terser-webpack-plugin');
  2. module.exports = {
  3. optimization: {
  4. minimizer: [
  5. new TerserPlugin({
  6. cache: true,
  7. parallel: true,
  8. sourceMap: true, // Must be set to true if using source-maps in production
  9. terserOptions: {
  10. // https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
  11. }
  12. }),
  13. ],
  14. }
  15. };

Or, as function:

  1. module.exports = {
  2. optimization: {
  3. minimizer: [
  4. (compiler) => {
  5. const TerserPlugin = require('terser-webpack-plugin');
  6. new TerserPlugin({ /* your config */ }).apply(compiler);
  7. }
  8. ],
  9. }
  10. };

optimization.splitChunks

object

对于动态导入模块,默认使用 webpack v4+ 提供的全新的通用分块策略(common chunk strategy)。请在 SplitChunksPlugin 页面中查看配置其行为的可用选项。

optimization.runtimeChunk

object string boolean

optimization.runtimeChunk 设置为 true"multiple",会为每个仅含有 runtime 的入口起点添加一个额外 chunk。此设置是如下设置的别名:

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. runtimeChunk: {
  5. name: entrypoint => `runtime~${entrypoint.name}`
  6. }
  7. }
  8. };

"single" 会创建一个在所有生成 chunk 之间共享的运行时文件。此设置是如下设置的别名:

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. runtimeChunk: {
  5. name: 'runtime'
  6. }
  7. }
  8. };

通过将 optimization.runtimeChunk 设置为 object,对象中可以设置只有 name 属性,其中属性值可以是名称或者返回名称的函数,用于为 runtime chunks 命名。

默认值是 false:每个入口 chunk 中直接嵌入 runtime。

对于每个 runtime chunk,导入的模块会被分别初始化,因此如果你在同一个页面中引用多个入口起点,请注意此行为。你或许应该将其设置为 single,或者使用其他只有一个 runtime 实例的配置。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. runtimeChunk: {
  5. name: entrypoint => `runtimechunk~${entrypoint.name}`
  6. }
  7. }
  8. };

optimization.noEmitOnErrors

boolean

在编译出错时,使用 optimization.noEmitOnErrors 来跳过生成阶段(emitting phase)。这可以确保没有生成出错误资源。而 stats 中所有 assets 中的 emitted 标记都是 false

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. noEmitOnErrors: true
  5. }
  6. };

如果你正在使用 webpack CLI,在此插件开启时,webpack 处理过程不会因为错误代码而退出。如果你希望在使用 CLI 时 webpack “失败(fail)”,请查看 bail 选项

optimization.namedModules

boolean: false

告知 webpack 使用可读取模块标识符(readable module identifiers),来帮助更好地调试。webpack 配置中如果没有设置此选项,默认会在 mode development 启用,在 mode production 禁用。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. namedModules: true
  5. }
  6. };

optimization.namedChunks

boolean: false

告知 webpack 使用可读取 chunk 标识符(readable chunk identifiers),来帮助更好地调试。webpack 配置中如果没有设置此选项,默认会在 mode development 启用,在 mode production 禁用。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. namedChunks: true
  5. }
  6. };

optimization.moduleIds

bool: false string: natural, named, hashed, size, total-size

Tells webpack which algorithm to use when choosing module ids. Setting optimization.moduleIds to false tells webpack that none of built-in algorithms should be used, as custom one can be provided via plugin. By default optimization.moduleIds is set to false.

The following string values are supported:

Option

Description

Option

natural

Description

Numeric ids in order of usage.

Option

named

Description

Readable ids for better debugging.

Option

hashed

Description

Short hashes as ids for better long term caching.

Option

size

Description

Numeric ids focused on minimal initial download size.

Option

total-size

Description

numeric ids focused on minimal total download size.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. moduleIds: 'hashed'
  5. }
  6. };

optimization.chunkIds

bool: false string: natural, named, size, total-size

Tells webpack which algorithm to use when choosing chunk ids. Setting optimization.chunkIds to false tells webpack that none of built-in algorithms should be used, as custom one can be provided via plugin. There are couple of defaults for optimization.chunkIds:

  • if optimization.occurrenceOrder is enabled optimization.chunkIds is set to 'total-size'
  • Disregarding previous if, if optimization.namedChunks is enabled optimization.chunkIds is set to 'named'
  • if none of the above, optimization.namedChunks will be defaulted to 'natural'

The following string values are supported:

Option

Description

Option

'natural'

Description

Numeric ids in order of usage.

Option

'named'

Description

Readable ids for better debugging.

Option

'size'

Description

Numeric ids focused on minimal initial download size.

Option

'total-size'

Description

numeric ids focused on minimal total download size.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. chunkIds: 'named'
  5. }
  6. };

optimization.nodeEnv

string bool: false

告知 webpack 将 process.env.NODE_ENV 设置为一个给定字符串。如果 optimization.nodeEnv 不是 false,则会使用 DefinePluginoptimization.nodeEnv 默认值取决于 mode,如果为 falsy 值,则会回退到 "production"

可能的值有:

  • 任何字符串:用于设置 process.env.NODE_ENV 的值。
  • false:不修改/设置 process.env.NODE_ENV的值。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. nodeEnv: 'production'
  5. }
  6. };

optimization.mangleWasmImports

bool: false

在设置为 true 时,告知 webpack 通过将导入修改为更短的字符串,来减少 WASM 大小。这会破坏模块和导出名称。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. mangleWasmImports: true
  5. }
  6. };

optimization.removeAvailableModules

bool: true

如果模块已经包含在所有父级模块中,告知 webpack 从 chunk 中检测出这些模块,或移除这些模块。将 optimization.removeAvailableModules 设置为 false 以禁用这项优化。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. removeAvailableModules: false
  5. }
  6. };

optimization.removeEmptyChunks

bool: true

如果 chunk 为空,告知 webpack 检测或移除这些 chunk。将 optimization.removeEmptyChunks 设置为 false 以禁用这项优化。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. removeEmptyChunks: false
  5. }
  6. };

optimization.mergeDuplicateChunks

bool: true

告知 webpack 合并含有相同模块的 chunk。将 optimization.mergeDuplicateChunks 设置为 false 以禁用这项优化。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. mergeDuplicateChunks: false
  5. }
  6. };

optimization.flagIncludedChunks

bool

告知 webpack 确定和标记出作为其他 chunk 子集的那些 chunk,其方式是在已经加载过较大的 chunk 之后,就不再去加载这些 chunk 子集。optimization.flagIncludedChunks 默认会在 production mode 中启用,其他情况禁用。

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. flagIncludedChunks: true
  5. }
  6. };

optimization.occurrenceOrder

bool

Tells webpack to figure out an order of modules which will result in the smallest initial bundle. By default optimization.occurrenceOrder is enabled in production mode and disabled elsewise.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. occurrenceOrder: false
  5. }
  6. };

optimization.providedExports

bool

Tells webpack to figure out which exports are provided by modules to generate more efficient code for export * from .... By default optimization.providedExports is enabled.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. providedExports: false
  5. }
  6. };

optimization.usedExports

bool

Tells webpack to determine used exports for each module. This depends on optimization.providedExports. Information collected by optimization.usedExports is used by other optimizations or code generation i.e. exports are not generated for unused exports, export names are mangled to single char identifiers when all usages are compatible. Dead code elimination in minimizers will benefit from this and can remove unused exports. By default optimization.usedExports is enabled in production mode and disabled elsewise.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. usedExports: true
  5. }
  6. };

optimization.concatenateModules

bool

Tells webpack to find segments of the module graph which can be safely concatenated into a single module. Depends on optimization.providedExports and optimization.usedExports. By default optimization.concatenateModules is enabled in production mode and disabled elsewise.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. concatenateModules: true
  5. }
  6. };

optimization.sideEffects

bool

Tells webpack to recognise the sideEffects flag in package.json or rules to skip over modules which are flagged to contain no side effects when exports are not used.

package.json

  1. {
  2. "name": "awesome npm module",
  3. "version": "1.0.0",
  4. "sideEffects": false
  5. }

Please note that sideEffects should be in the npm module’s package.json file and doesn’t mean that you need to set sideEffects to false in your own project’s package.json which requires that big module.

optimization.sideEffects depends on optimization.providedExports to be enabled. This dependency has a build time cost, but eliminating modules has positive impact on performance because of less code generation. Effect of this optimization depends on your codebase, try it for possible performance wins.

By default optimization.sideEffects is enabled in production mode and disabled elsewise.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. sideEffects: true
  5. }
  6. };

optimization.portableRecords

bool

optimization.portableRecords tells webpack to generate records with relative paths to be able to move the context folder.

By default optimization.portableRecords is disabled. Automatically enabled if at least one of the records options provided to webpack config: recordsPath, recordsInputPath, recordsOutputPath.

webpack.config.js

  1. module.exports = {
  2. //...
  3. optimization: {
  4. portableRecords: true
  5. }
  6. };

进一步阅读


贡献人员

EugeneHlushko EugeneHlushko byzyk byzyk dhurlburtusa dhurlburtusa jeremenichelli jeremenichelli madhavarshney madhavarshney simon04 simon04