Optimization

Webpack runs optimizations for you depending on the chosen mode, still all optimizations are available for manual configuration and overrides.

optimization.checkWasmTypes

boolean

Tells webpack to check the incompatible types of WebAssembly modules when they are imported/exported.

The default value of optimization.checkWasmTypes depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    checkWasmTypes: false,
  },
};

optimization.chunkIds

'natural' | 'named' | 'size' | 'total-size' | 'deterministic' | false

  • false: disable webpack's built-in chunk id algorithm
  • one of the following values:
    • 'natural'
    • 'named'
    • 'size'
    • 'total-size'
    • 'deterministic'

Tells Webpack which algorithm to use for 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 a couple of defaults for optimization.chunkIds:

The default value of optimization.chunkIds depends on the mode:

ModeDefault
"production"'deterministic'
"development"'named'
"none"'natural'

The following string values are supported:

OptionDescription
'natural'Numeric ids in order of usage.
'named'Readable ids for better debugging.
'deterministic'Short numeric ids which will not be changing between compilation. Good for long term caching. Enabled by default for production mode.
'size'Numeric ids focused on minimal initial download size.
'total-size'numeric ids focused on minimal total download size.

webpack.config.js

export default {
  // ...
  optimization: {
    chunkIds: "named",
  },
};

By default, ids are hashed into an id space of 10³ (maxLength: 3) when optimization.chunkIds is set to 'deterministic'; the space grows by a factor of 10 when needed. To override the default behaviour, set optimization.chunkIds to false and use the webpack.ids.DeterministicChunkIdsPlugin.

webpack.config.js

export default {
  // ...
  optimization: {
    chunkIds: false,
  },
  plugins: [
    new webpack.ids.DeterministicChunkIdsPlugin({
      maxLength: 5,
    }),
  ],
};

webpack.ids.DeterministicChunkIdsPlugin is the plugin behind chunkIds: 'deterministic'. It hashes each chunk's name — its path relative to context, so ids don't change when the project moves — into a number, and it accepts these options:

OptionTypeDefaultDescription
contextstringcompiler.contextThe directory chunk names are made relative to before hashing.
maxLengthnumber3The number of digits ids start with. webpack keeps multiplying that range by ten until it is roughly 20 times the number of chunks, which keeps collisions rare.

optimization.concatenateModules

boolean object

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.

The default value of optimization.concatenateModules depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    concatenateModules: true,
  },
};

Since webpack 5.109.0, CommonJS modules with statically analyzable exports are concatenated as well, and an object form is accepted for advanced options:

  • commonjs (boolean = true): Also concatenate CommonJS modules with statically analyzable exports. Set it to false to restrict concatenation to ECMAScript modules, matching the behavior of earlier webpack versions.

webpack.config.js

export default {
  // ...
  optimization: {
    concatenateModules: {
      commonjs: false,
    },
  },
};

optimization.emitOnErrors

boolean

Use the optimization.emitOnErrors to emit assets whenever there are errors while compiling. This ensures that erroring assets are emitted. Critical errors are emitted into the generated code and will cause errors at runtime.

The default value of optimization.emitOnErrors depends on the mode:

ModeDefault
"production"false
"development"true
"none"true

webpack.config.js

export default {
  // ...
  optimization: {
    emitOnErrors: true,
  },
};

optimization.avoidEntryIife

boolean

5.95.0+

Use optimization.avoidEntryIife ...

optimization.avoidEntryIife can remove the IIFE when a chunk has multiple inlined entry modules, or a single inlined entry module alongside other modules in the chunk. An IIFE is still emitted when an inlined module needs to be in strict mode while the rest of the chunk is not, or when a module uses a non-standard name for the exports object (its exportsArgument).

The default value of optimization.avoidEntryIife depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    avoidEntryIife: true,
  },
};

optimization.flagIncludedChunks

boolean

Tells webpack to determine and flag chunks which are subsets of other chunks in a way that subsets don't have to be loaded when the bigger chunk has been already loaded.

The default value of optimization.flagIncludedChunks depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    flagIncludedChunks: true,
  },
};

optimization.innerGraph

boolean

optimization.innerGraph tells webpack whether to conduct inner graph analysis for unused exports.

The default value of optimization.innerGraph depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    innerGraph: false,
  },
};

optimization.inlineExports

boolean

5.108.0+

Inline ESM exports that bind to small primitive constants (a null, undefined, boolean, number or string of at most 6 bytes) at every import site, replacing the imported binding with the literal value. Once every import is replaced, the import dependency becomes inactive, the export turns unused, and dead-code elimination can drop the export and, if the module is side-effect free, the whole module.

The default value of optimization.inlineExports depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    inlineExports: true,
  },
};

This happens in two steps. Given these modules:

// flags.js
export const DEBUG = false; // a ≤6-byte boolean
// app.js
import { DEBUG } from "./flags.js";

if (DEBUG) doSomething();

First, every reference to the imported binding is replaced with its literal value (inlining):

// app.js (conceptual result)
if (false) doSomething();

Then, because no import references DEBUG anymore, the export const DEBUG is left unused and dead-code elimination drops it. If flags.js has no side effects, the whole module is removed too. The consuming code can additionally collapse the now-constant branch (if (false) ...).

Inlining also enables cross-module dead-branch skipping: when an imported constant is statically inlinable, webpack evaluates the condition that guards a branch and skips the dependencies that live only in the provably-dead branch (ESM import specifiers, require() calls, and dynamic import() calls), so the unreachable modules are never added to the bundle.

// env.js
export const isDEV = false;
// app.js
import { devOnly } from "./dev-tools";
import { isDEV } from "./env";
import { prodOnly } from "./prod-tools";

export const tools = isDEV ? devOnly : prodOnly;

Because isDEV inlines to false, the devOnly branch is dead, so ./dev-tools is never bundled. The same holds for require() and dynamic import() calls that sit only in the dead branch.

optimization.mangleExports

boolean 'deterministic' | 'size'

optimization.mangleExports allows to control export mangling.

The default value of optimization.mangleExports depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

The following values are supported:

OptionDescription
'size'Short names - usually a single char - focused on minimal download size.
'deterministic'Short names - usually two chars - which will not change when adding or removing exports. Good for long term caching.
trueSame as 'deterministic'
falseKeep original name. Good for readability and debugging.

webpack.config.js

export default {
  // ...
  optimization: {
    mangleExports: true,
  },
};

optimization.mangleWasmImports

boolean = false

When set to true tells webpack to reduce the size of WASM by changing imports to shorter strings. It mangles module and export names.

webpack.config.js

export default {
  // ...
  optimization: {
    mangleWasmImports: true,
  },
};

optimization.mergeDuplicateChunks

boolean = true

Tells webpack to merge chunks which contain the same modules. Setting optimization.mergeDuplicateChunks to false will disable this optimization.

webpack.config.js

export default {
  // ...
  optimization: {
    mergeDuplicateChunks: false,
  },
};

optimization.minimize

boolean object

Tell webpack to minimize the bundle using the MinimizerPlugin or the plugin(s) specified in optimization.minimizer.

The default value of optimization.minimize depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    minimize: false,
  },
};

Per-asset-type options

5.110.0+

An object enables minimizing and configures the built-in minimizer per asset type. An absent type is minimized with its defaults, and false disables minimizing that type alone:

The types are javascript, css, html, json and xml (SVG and XML). The CSS and HTML minimizers only run when the corresponding built-in support is enabled (experiments.css, experiments.html), and webpack steps aside for a minimizer already configured for those assets, so an existing css-minimizer-webpack-plugin setup keeps owning its own.

webpack.config.js

export default {
  // ...
  optimization: {
    minimize: {
      javascript: {/* handed to the JavaScript minimizer as-is */},
      css: {
        comments: false,
      },
      html: false,
      json: true,
      xml: { removeMetadata: true },
    },
  },
};

optimization.minimize.css

false object

What the built-in CSS minimizer may do beyond the transforms that always apply. Every transform that preserves what the stylesheet means is on by default; the ones that change text a script can read back, or that rarely pay for themselves once the asset is compressed, are off until asked for.

OptionTypeDefaultDescription
commentsboolean | 'all' | 'some' | string | RegExp | function'some'Which comments survive. 'some' keeps a /*! banner and @license / @preserve; a pattern or predicate stands in for that rule.
charset'auto' | false'auto'5.112.0+ Open a .css asset with @charset "UTF-8" only when its output holds a non-ASCII character. false writes no @charset and writes escaped astral characters (an icon font's content: "\F0A86") as the characters themselves — set it only where the stylesheet is always served or linked as UTF-8.
colorFallbacksbooleantrue5.111.0+ Write a color the browserslist target cannot read as an extra declaration before it, in a spelling it does read (a hex fallback ahead of an oklch()).
foldCasebooleantrue5.111.0+ Write at-rule, property, pseudo, function, unit and keyword names in lowercase; names the author chose are left alone.
lowerUnsupportedbooleantrue5.111.0+ Write a spelling the browserslist target cannot read as an equal one it can (inset as its longhands, a media range as min-/max-, …).
mergeLonghandsbooleantrueWrite a family of longhands as the one shorthand that sets them.
mergeRulesbooleantrueJoin rules nothing stands between, and fold at-rules sharing a prelude.
normalizeQuotesbooleantrueUse whichever quoting needs fewer escapes, and drop quotes where the value is still one token.
reduceFunctionsbooleantrueCompute calc() and other math over constants, identity transforms, implied gradient stops, and named easings.
removeDeadRulesbooleantrueDrop a rule or declaration nothing can read.
reorderDeclarationsbooleantrue5.112.0+ Print a rule's declarations in one order by property family, so blocks setting the same things read alike and compress smaller. Declarations whose relative order is observable (a property and its fallback, a shorthand and its longhands, logical and physical sides) keep it.
rewriteEscapesbooleantrue5.111.0+ Write an escaped identifier the shortest way that names the same thing (grid-area:\66oot → grid-area:foot).
shortenColorsbooleantrueWrite each color in the shortest spelling of the same value.
shortenMediaQueriesbooleantrueWrite a media feature in its range spelling where the target reads one.
shortenNumbersbooleantrueWrite each number in its shortest equal spelling.
shortenSelectorsbooleantrueRewrite a selector into an equal, shorter one.
shortenValuesbooleantrueWrite a value the shortest way its property's grammar allows.
vendorPrefixesbooleantrueMaintain vendor prefixes for the browserslist target — add what a selected browser needs, drop the rest.
convertLengthUnitsbooleanfalseRewrite a length into a shorter unit it is exactly equal in (16px → 1pc).
convertApproximateColorsbooleanfalse5.112.0+ Write a polar or Lab color (oklch(), lab(), hwb(), …) as the nearest hex even where hex only approximates it. shortenColors already converts every color whose hex is exact; this also takes channels on a rounding boundary and colors outside the sRGB gamut, which hex can only clip.
customMediabooleanfalse5.112.0+ Resolve @custom-media (@custom-media --wide (width>400px) with @media (--wide) becomes @media (width>400px)). module.parser.css.customMedia already does this for every stylesheet webpack parses, so this is for a .css asset that reached the minimizer unparsed — emitted by asset/resource or copied in.
customSelectorsbooleanfalse5.112.0+ Resolve @custom-selector, writing the list a name stands for as :is(…) where the target reads :is(). Like customMedia, for stylesheets webpack did not parse.
dropOverriddenDeclarationsbooleanfalse5.112.0+ Drop a declaration a later one in the same block overrides even when no browserslist target is selected, assuming today's Chromium, Gecko and WebKit. With a target this already happens wherever every selected browser reads the later value. Gives up fallback pairs: color:#c65d06;color:lab(50% 100 -100) loses the hex.
extractCommentsboolean | 'all' | 'some' | string | RegExp | functionundefined5.112.0+ Move comments out of a .css asset into the [file].LICENSE.txt the minimizer writes for JavaScript, leaving a one-line banner pointing at it. Takes terser's values: true / 'some' move /*! banners and @preserve / @lic comments, 'all' every comment, a pattern or a ({ value, line, col }) => boolean predicate the ones it matches. Unset, the minimizer plugin's own extractComments applies. Inline <style> and style="" keep their comments.
mergeDistantRulesbooleanfalse5.111.0+ Give a rule the selectors of a later one printing the same block, past the rules standing between them; off because it reorders the cascade.
pseudoClassesobjectundefined5.111.0+ Pseudo-classes to write as ordinary classes instead ({ "focus-visible": "focus-visible" }), for a script to apply where the engine reads no such pseudo.
rewriteCustomPropertiesbooleanfalseShorten custom property values, which are otherwise written back exactly as authored.
rewriteDirSelectorbooleanfalse5.111.0+ Write a :dir() the browserslist target cannot read as the [dir] attribute selector it approximates.
unusedSymbolsstring[]undefined5.111.0+ Class, id, @keyframes and custom property names a whole-project analysis found unused, which the minimizer removes.

optimization.minimize.html

false object

What the built-in HTML minimizer may do. As with CSS, everything that keeps the document's DOM is on by default and the transforms that change what a script or a selector reads back are opt-in.

OptionTypeDefaultDescription
collapseBooleanAttributesboolean | 'all'trueWrite disabled="disabled" as the bare name the spec canonicalizes it to. 'all' 5.111.0+ also rewrites any other value, including checked="false".
commentsboolean | 'all' | 'some' | string | RegExp | function'some'Which comments survive — 'some' keeps none, since every comment an HTML parser reads is inert.
extractCommentsboolean | 'all' | 'some' | string | RegExp | functionundefined5.112.0+ Move comments out of an .html asset into its [file].LICENSE.txt, leaving a <!-- … --> banner at the end of the document so the doctype stays first. Takes the same values as minimize.css.extractComments. Conditional comments, server-side includes and <?…?> directives are code and are never moved.
normalizeAttributeQuotesbooleantrueWrite an attribute value with whichever delimiters cost least.
normalizeEnumeratedAttributesbooleantrueFold an enumerated attribute's value to the keyword it names.
normalizeListAttributesbooleantrueNormalize list-shaped attribute values (class, rel, srcset, the viewport content, …).
normalizeNumericAttributesbooleantrueWrite an integer attribute the one way its own rules read it.
normalizeUrlAttributesbooleantrue5.111.0+ Drop the ASCII whitespace around a URL attribute value (href, src, action, …), which resolving the URL skips anyway.
removeImpliedTagsboolean | 'smart' | 'all''smart'How much of the <html> / <head> / <body> shell may be left out.
removeOptionalTagsbooleantrueLeave out other tags the parser can imply.
collapseWhitespaceboolean | 'conservative' | 'smart' | 'all'falseCollapse runs of whitespace; true means 'conservative', which never removes whitespace entirely. 'smart' also drops it against a block element's edge; 'all' at every text node's edges. Off because textContent and CSS the minimizer cannot see (white-space: pre) read the runs back.
mergeScriptsbooleanfalse5.111.0+ Print a run of adjacent bare <script> elements as one, joined by a ;.
mergeStylesbooleanfalsePrint a run of adjacent <style> elements as one sheet.
minifyConditionalCommentsbooleanfalseMinify the markup inside a downlevel-hidden conditional comment.
removeEmptyAttributesbooleanfalseDrop an attribute whose empty value leaves it in the state its absence gives.
removeEmptyElementsbooleanfalseDrop an element with no children and no attributes.
removeRedundantAttributesboolean | 'smart' | 'all'falseDrop an attribute whose value is the element's own default. 'smart' only touches non-rendering markers.
sortAttributesbooleanfalsePrint attributes in a fixed order so shared runs compress better across pages.
sortTokenListsbooleanfalsePrint set-like token lists (class, rel, …) in token order, for the same reason.

webpack.config.js

export default {
  mode: "production",
  experiments: { html: true, css: true },
  optimization: {
    minimize: {
      html: {
        collapseWhitespace: "smart",
        removeRedundantAttributes: "smart",
        sortAttributes: true,
        sortTokenLists: true,
      },
    },
  },
};

optimization.minimize.javascript

false object

Handed to the JavaScript minimizer as-is, defaulting to { compress: { passes: 2 } }; false disables JavaScript minimizing while leaving CSS and HTML minimized. The object takes terser's options — compress, mangle, format, parse, sourceMap, module, ecma, toplevel, keepClassnames, keepFnames and the rest.

Since webpack 5.112.0, with experiments.futureDefaults webpack minifies JavaScript with its own terser-compatible minifier instead of terser, so an existing terser configuration keeps working. Without futureDefaults, terser does the minifying. Since webpack 5.113.0 the built-in minifier also honors the compress options pure_funcs, pure_getters, drop_console, global_defs, top_retain, unused, inline and keep_fargs, and writes source maps in the same pass.

Since webpack 5.113.0, option names can be written in camelCase (dropConsole, pureFuncs, globalDefs, keepFnames, …). terser's snake_case names stay accepted as aliases, and where both spellings are given the camelCase one wins. When terser does the minifying, webpack converts the names back before handing them over.

webpack.config.js

export default {
  mode: "production",
  optimization: {
    minimize: {
      javascript: {
        // camelCase names need webpack 5.113.0+; use drop_console, pure_funcs
        // and global_defs on earlier versions.
        compress: {
          passes: 3,
          dropConsole: ["log", "debug"],
          pureFuncs: ["assert"],
          globalDefs: { DEBUG: false },
        },
        mangle: { keepClassnames: true },
        format: { comments: false },
      },
    },
  },
};

optimization.minimize.json

boolean

5.112.0+

Minimize emitted .json assets by re-serializing them without whitespace. Defaults to true with experiments.futureDefaults and false otherwise, so turn it on explicitly to shrink JSON files copied or emitted as asset modules:

export default {
  optimization: {
    minimize: {
      json: true,
    },
  },
};

optimization.minimize.xml

false object

5.112.0+

Minimize emitted .svg and .xml assets — SVG icons, sprites, illustrations and other XML — with webpack's built-in SVG minifier, so svgo, svgo-loader or image-minimizer-webpack-plugin are not needed for typical icon pipelines. It is off unless an object is given, or experiments.futureDefaults is set; false disables it.

The same switches apply to an SVG data: URL in CSS or HTML, and an <svg> inlined in an HTML page takes removeMetadata, shortenNumbers and shortenPathData. Stylesheets inside an SVG or XHTML document are minified with the minimize.css options for the target's browsers.

As with CSS and HTML, the transforms that draw exactly the same image are on by default, and anything that changes what a script, a stylesheet, assistive technology or another document can observe — IDs, element types, attribute presence, rounded geometry, metadata — is off until asked for. Options that would be unsafe for a document skip it automatically when it contains stylesheets, scripts, animations or a DTD where noted.

Enabled by default 5.113.0+

OptionTypeDefaultDescription
collapseWhitespacebooleantrueRemove whitespace-only text in SVG containers, which renders nothing. Text content and foreign content keep theirs, and it stays where a stylesheet reads :empty.
removeUnusedNamespacesbooleantrueDrop prefixed namespace declarations no name or value uses (xmlns:sketch, xmlns:inkscape, …).
shortenColorsbooleantrueWrite opaque presentation colors in their shortest spelling (fill="#ff0000" → fill="red"), keeping paint servers and context-fill / context-stroke.
shortenNumbersbooleantrueShorten geometry and transform numbers and separators without rounding (0.50 → .5).
shortenPathDatabooleantrueCompact path data — numbers, repeated commands, separators — without rounding, and drop segments that draw nothing where nothing can observe them.
commentsboolean | 'all' | 'some' | string | RegExp | function'some'Which comments survive. 'some' keeps a legal notice — a comment opening with ! or annotated @license / @preserve; true / 'all' keeps every comment, false none.

Precision and geometry 5.113.0+

OptionTypeDefaultDescription
precisionnumberundefinedRound geometry, path data, transforms and presentation numbers to this many decimals (0–15) wherever shortenNumbers and shortenPathData apply. Points round where they land, so error never accumulates. svgo rounds to 3.
anglePrecisionnumberundefinedWith convertTransforms, round rotation angles to this many decimals, like svgo's degPrecision.
convertTransformsbooleanfalseRecompose each transform list as the shortest one matching it within precision (a matrix() can become rotate(-45 261.757 -252.243)).
applyTransformsbooleanfalseBake a path's transform into its path data, scaling strokes it scales. Skips paths with IDs, styles, markers, clip paths, masks, filters or url() paints.
convertCurvesToArcsboolean | 'loose'falseWith shortenPathData, write cubic curves that stay within precision of a circle as arcs, other cubics as quadratics, and near-flat arcs as lines. 'loose' fits as svgo's makeArcs does.
convertShapesbooleanfalseWrite <line>, <polyline> and <polygon> as shorter <path>s with identical coordinates, and equal-radius ellipses as circles.
mergePathsbooleanfalseMerge adjacent disjoint axis-aligned stroked lines with the same paint into one path.
mergeDisjointPathsbooleanfalseMerge adjacent paths of any shape with the same attributes whose bounds, stroke included, do not overlap. Anti-aliasing can blend a shared edge pixel differently.
reusePathsbooleanfalseReference duplicate leaf paths through <use href> instead of repeating them.
removeOffCanvasPathsbooleanfalseDrop unnamed paths that lie wholly outside the root viewBox. A viewport of another aspect ratio can still show them.

Structure and styles 5.113.0+

OptionTypeDefaultDescription
cleanupIdsbooleanfalseRemove IDs nothing in the document references and shorten the rest, rewriting href, url() and ID-list references. Breaks a sprite's icons.svg#name or getElementById from outside.
cleanupStructurebooleanfalseCollapse groups, hoist inherited attributes all children share, inline presentation declarations, and remove empty text, unnamed definitions and redundant attributes.
inlineStylesbooleanfalseMove <style> rules into the style attributes of the elements they match, in cascade order, then drop the stylesheet and the classes it named, where the result is no larger.
inlineStylePseudoClassesstring[]undefinedWith inlineStyles, also inline rules using these pseudo-classes (such as :hover) as if they always held, like svgo's usePseudos.
collapseAttributeWhitespacebooleanfalseTrim every attribute value and collapse inner whitespace runs, like svgo's cleanupAttrs.
removeEmptyAttributesbooleanfalseRemove empty class, id, style and other empty attributes that read as absent.
removeEmptyElementsbooleanfalseRemove empty <g> and <defs> containers.
removeHiddenElementsbooleanfalseRemove ID-free content that renders nothing: display="none", zero opacity, zero-size shapes, shapes painting neither fill nor stroke, …
sortAttributesbooleanfalse5.112.0+ Print attributes with the document's most common names first, so shared runs compress better.
sortDefinitionsbooleanfalseSort adjacent resource definitions inside <defs> by type and ID.
sortSymbolsbooleanfalseSort adjacent <symbol> definitions by ID.

Removing content 5.113.0+

OptionTypeDefaultDescription
removeDimensionsbooleanfalseRemove the root width and height, moving them into a missing viewBox, so the image scales to its box.
removeViewBoxbooleanfalseRemove a root viewBox that restates plain width and height. The image then no longer scales when CSS resizes it.
removeDoctypebooleanfalseRemove a DOCTYPE without an internal subset.
removeMetadatabooleanfalseRemove <metadata> elements, which may carry licensing data.
removeEditorDatabooleanfalseRemove elements and attributes in known editor namespaces (Inkscape, Sodipodi, Illustrator, Sketch, Figma, …).
removeTitlesbooleanfalseRemove <title> elements. They name the image for assistive technology and tooltips.
removeDescriptionsbooleanfalseRemove <desc> elements. They describe the image for assistive technology.
removeScriptsbooleanfalseRemove <script>, event handler attributes, javascript: URLs and links to HTML or SVG data: documents, for SVG that must not run code.
removeRasterImagesbooleanfalseRemove <image> elements referencing JPEG, PNG or GIF images.
removeUnknownElementsbooleanfalseRemove SVG-namespace elements no SVG specification defines.
removeUnknownAttributesboolean | 'unsafe'falseRemove unprefixed attributes no SVG, ARIA or animation specification defines, keeping data-, aria-, role and event handlers. 'unsafe' drops role too.
removeDeprecatedAttributesboolean | 'unsafe'falseWrite xml:lang as lang; 'unsafe' drops xml:lang instead.
removeXlinkbooleanfalseWrite xlink:href as the SVG 2 href (and xlink:show / xlink:title as their SVG 2 forms) so the XLink namespace can go. Browsers before SVG 2 need xlink:href.
removeElements{ id?: string[], class?: string[] }undefinedRemove elements with these IDs or classes, with their content.
removeAttributesstring[]undefinedRemove attributes matching element:attribute:value patterns, each part a case-insensitive regular expression; * or a missing part matches anything.

An svgo-like setup for icons that are only ever used as images:

webpack.config.js

export default {
  mode: "production",
  module: {
    rules: [{ test: /\.svg$/, type: "asset/resource" }],
  },
  optimization: {
    minimize: {
      xml: {
        precision: 3,
        convertTransforms: true,
        convertShapes: true,
        cleanupIds: true,
        cleanupStructure: true,
        inlineStyles: true,
        removeMetadata: true,
        removeEditorData: true,
        removeDoctype: true,
        removeXlink: true,
      },
    },
  },
};

optimization.minimizeOptions

object

5.110.0+

The same per-asset-type object as above, set separately from optimization.minimize. Passing the object to minimize is a shorthand: webpack normalizes minimize: { css: … } to minimize: true plus minimizeOptions: { css: … }, so the two forms below are equivalent.

webpack.config.js

export default {
  // ...
  optimization: {
    minimize: true,
    minimizeOptions: {
      css: {
        comments: false,
      },
    },
  },
};

Reach for it when minimizing is switched on elsewhere — by the mode default or by a config that is merged with yours — and you only want to adjust how it is done. It is also the property plugins see, since optimization.minimize is always a boolean after normalization.

optimization.minimizer

(MinimizerPlugin | ((compiler: Compiler) => void) | '...' | false | 0 | '' | null | undefined)[]

Allows you to override the default minimizer by providing a different one or more customized MinimizerPlugin instances. Starting with webpack 5.87.0 falsy values can be used to conditionally disable specific minimizers.

webpack.config.js

import MinimizerPlugin from "minimizer-webpack-plugin";

export default {
  optimization: {
    minimizer: [
      new MinimizerPlugin({
        parallel: true,
        minimizerOptions: {
          // https://github.com/webpack/minimizer-webpack-plugin#minimizeroptions
        },
      }),
    ],
  },
};

Or, as function:

import MinimizerPlugin from "minimizer-webpack-plugin";

export default {
  optimization: {
    minimizer: [
      (compiler) => {
        new MinimizerPlugin({/* your config */}).apply(compiler);
      },
    ],
  },
};

By default, webpack would set optimization.minimizer to the following value:

import MinimizerPlugin from "minimizer-webpack-plugin";

const minimizer = [
  {
    apply: (compiler) => {
      new MinimizerPlugin({
        minimizerOptions: {
          compress: {
            passes: 2,
          },
        },
      }).apply(compiler);
    },
  },
];

Which can be accessed with '...' in case you want to keep it when customizing optimization.minimizer:

export default {
  optimization: {
    minimizer: [new CssMinimizer(), "..."],
  },
};

Basically, '...' is a shortcut to access the default configuration value webpack would otherwise set for us.

optimization.moduleIds

'natural' | 'named' | 'deterministic' | 'size' | false

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.

The default value of optimization.moduleIds depends on the mode:

ModeDefault
"production"'deterministic'
"development"'named'
"none"'natural'

The following string values are supported:

OptionDescription
naturalNumeric ids in order of usage.
namedReadable ids for better debugging.
deterministicModule names are hashed into small numeric values.
sizeNumeric ids focused on minimal initial download size.

webpack.config.js

export default {
  // ...
  optimization: {
    moduleIds: "deterministic",
  },
};

The deterministic option is useful for long term caching, but still results in smaller bundles compared to hashed. The id space is sized so that ids fill at most 5% of it. By default ids are hashed into an id space of 10³ (maxLength: 3) when optimization.moduleIds is set to deterministic, and the space grows by a factor of 10 when needed. To override the default behaviour set optimization.moduleIds to false and use the webpack.ids.DeterministicModuleIdsPlugin.

webpack.config.js

export default {
  // ...
  optimization: {
    moduleIds: false,
  },
  plugins: [
    new webpack.ids.DeterministicModuleIdsPlugin({
      maxLength: 5,
    }),
  ],
};

webpack.ids.DeterministicModuleIdsPlugin is the plugin behind moduleIds: 'deterministic'. It hashes each module's request — made relative to context, so ids survive a checkout in another directory — into a number, and it accepts these options:

OptionTypeDefaultDescription
contextstringcompiler.contextThe directory module names are made relative to before hashing.
test(module: Module) => booleanall modulesRestricts the plugin to the modules it returns true for, so another plugin can name the rest.
maxLengthnumber3The number of digits ids start with. webpack keeps multiplying that range by ten until it is roughly 20 times the number of modules, which keeps collisions rare.
fixedLengthbooleanfalseKeeps the id space at maxLength digits instead of growing it.
saltnumber0Mixed into the hash. Change it to move every id, for example to work around a collision.
failOnConflictbooleanfalseFails the build on a colliding id instead of rehashing it.

The id plugins

Each value of moduleIds and chunkIds is implemented by a plugin under webpack.ids, which you can also use directly after setting the option to false. They are what the webpack 4 plugins of similar names became:

PluginEquivalent toOptions
webpack.ids.NaturalModuleIdsPluginmoduleIds: 'natural'—
webpack.ids.NamedModuleIdsPluginmoduleIds: 'named'context
webpack.ids.DeterministicModuleIdsPluginmoduleIds: 'deterministic'see above
webpack.ids.OccurrenceModuleIdsPluginmoduleIds: 'size'prioritiseInitial
webpack.ids.NamedChunkIdsPluginchunkIds: 'named'context, delimiter
webpack.ids.DeterministicChunkIdsPluginchunkIds: 'deterministic'see above
webpack.ids.OccurrenceChunkIdsPluginchunkIds: 'size'prioritiseInitial
webpack.ids.ChunkModuleIdRangePlugin—name, order, start, end — assigns ids in a range to the modules of one chunk

context makes the generated names relative to a directory other than the compiler's, and prioritiseInitial gives modules of initial chunks the shorter ids.

optimization.nodeEnv

string false

Tells webpack to set process.env.NODE_ENV to a given string value. optimization.nodeEnv uses DefinePlugin unless set to false.

The default value of optimization.nodeEnv depends on the mode:

ModeDefault
"production"'production'
"development"'development'
"none"false

Possible values:

  • any string: the value to set process.env.NODE_ENV to.
  • false: do not modify/set the value of process.env.NODE_ENV.

webpack.config.js

export default {
  // ...
  optimization: {
    nodeEnv: "production",
  },
};

optimization.portableRecords

boolean

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

export default {
  // ...
  optimization: {
    portableRecords: true,
  },
};

optimization.providedExports

boolean

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

export default {
  // ...
  optimization: {
    providedExports: false,
  },
};

optimization.realContentHash

boolean

Adds an additional hash compilation pass after the assets have been processed to get the correct asset content hashes. If realContentHash is set to false, internal data is used to calculate the hash and it can change when assets are identical.

The default value of optimization.realContentHash depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    realContentHash: false,
  },
};

optimization.removeAvailableModules

boolean = false

Tells webpack to detect and remove modules from chunks when these modules are already included in all parents. Setting optimization.removeAvailableModules to true will enable this optimization.

webpack.config.js

export default {
  // ...
  optimization: {
    removeAvailableModules: true,
  },
};

optimization.removeEmptyChunks

boolean = true

Tells webpack to detect and remove chunks which are empty. Setting optimization.removeEmptyChunks to false will disable this optimization.

webpack.config.js

export default {
  // ...
  optimization: {
    removeEmptyChunks: false,
  },
};

optimization.runtimeChunk

object string boolean

Setting optimization.runtimeChunk to true or 'multiple' adds an additional chunk containing only the runtime to each entrypoint. This setting is an alias for:

webpack.config.js

export default {
  // ...
  optimization: {
    runtimeChunk: {
      name: (entrypoint) => `runtime~${entrypoint.name}`,
    },
  },
};

The value 'single' instead creates a runtime file to be shared for all generated chunks. This setting is an alias for:

webpack.config.js

export default {
  // ...
  optimization: {
    runtimeChunk: {
      name: "runtime",
    },
  },
};

By setting optimization.runtimeChunk to object it is only possible to provide the name property which stands for the name or name factory for the runtime chunks.

Default is false: each entry chunk embeds runtime.

webpack.config.js

export default {
  // ...
  optimization: {
    runtimeChunk: {
      name: (entrypoint) => `runtimechunk~${entrypoint.name}`,
    },
  },
};

optimization.sideEffects

boolean 'flag'

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

{
  "name": "awesome npm module",
  "version": "1.0.0",
  "sideEffects": false
}

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.

The default value of optimization.sideEffects depends on the mode:

ModeDefault
"production"true
"development"'flag'
"none"'flag'

webpack.config.js

export default {
  // ...
  optimization: {
    sideEffects: true,
  },
};

To only use the manual flag and do not analyse source code:

export default {
  // ...
  optimization: {
    sideEffects: "flag",
  },
};

optimization.splitChunks

object

By default webpack v4+ provides new common chunks strategies out of the box for dynamically imported modules. See available options for configuring this behavior in the SplitChunksPlugin page.

optimization.usedExports

boolean 'global'

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.

The default value of optimization.usedExports depends on the mode:

ModeDefault
"production"true
"development"false
"none"false

webpack.config.js

export default {
  // ...
  optimization: {
    usedExports: false,
  },
};

To opt-out from used exports analysis per runtime:

export default {
  // ...
  optimization: {
    usedExports: "global",
  },
};
Edit this page·
« Previous
Resolve
Next »
Plugins

14 Contributors

EugeneHlushkojeremenichellisimon04byzykmadhavarshneydhurlburtusajamesgeorge007anikethsahasnitin315pixel-raychenxsanRoberto14hai-xshivxmsharma