For AI agents: the complete documentation index is available at https://rspack.rs/llms.txt, the full documentation bundle is available at https://rspack.rs/llms-full.txt, and this page is available as Markdown at https://rspack.rs/config/optimization.md.
close

Optimization

Rspack will select appropriate optimization configuration based on the mode. You can also customize the configuration via optimization.

optimization.avoidEntryIife

  • Type: boolean
  • Default:false

Use optimization.avoidEntryIife to avoid wrapping the entry module in an IIFE when it is required (search for "This entry needs to be wrapped in an IIFE because" in rspack_plugin_javascript). This approach helps optimize performance for JavaScript engines and helps tree shaking when building ESM libraries.

Currently, optimization.avoidEntryIife can only optimize a single entry module along with other modules.

rspack.config.mjs
export default {
  optimization: {
    avoidEntryIife: true,
  },
};
Warning

The ⁠optimization.avoidEntryIife option can negatively affect build performance. If you prioritize build performance over these optimizations, consider not enabling this option.

optimization.chunkIds

  • Type: false | 'natural' | 'named' | 'deterministic' | 'compact-hashed' | 'size' | 'total-size'
  • Default:development mode is'named', production mode is'deterministic'

Tells Rspack which algorithm to use when generating chunk ids.

The following values are supported:

optiondescription
'natural'Use 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. By default a minimum length of 3 digits is used.
'compact-hashed'Use the shortest available prefix of a stable lowercase alphanumeric hash.
'size'Use numeric ids to make the initial download package smaller.
'total-size'Use numeric ids to make the overall download package smaller.
falseDisable Rspack's built-in chunk id algorithm.
rspack.config.mjs
export default {
  optimization: {
    chunkIds: 'deterministic',
  },
};

Custom JavaScript plugins cannot currently assign chunk IDs. When you set chunkIds to false, add a chunk ID plugin from rspack.ids to plugins:

rspack.config.mjs
import { rspack } from '@rspack/core';

export default {
  optimization: {
    chunkIds: false,
  },
  plugins: [new rspack.ids.CompactHashedChunkIdsPlugin()],
};

The compact-hashed option uses the shortest available prefix of a stable lowercase alphanumeric hash as the chunk id, balancing long-term caching, bundle size, and runtime performance.

Deprecated alias

compat-hashed was available in Rspack 2.2.0. It is deprecated and was renamed to compact-hashed in Rspack 2.2.1. It remains available as a compatibility alias.

rspack.config.mjs
export default {
  optimization: {
    chunkIds: 'compact-hashed',
  },
};
Tip

The compact-hashed option is available in Rspack 2.2.1 and later.

optimization.concatenateModules

Tells Rspack 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.

rspack.config.mjs
export default {
  optimization: {
    concatenateModules: false,
  },
};

optimization.emitOnErrors

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

rspack.config.mjs
export default {
  optimization: {
    emitOnErrors: true,
  },
};

optimization.inlineExports

Performs cross-module inline optimization for:

  1. Exported top-level constant values that can be statically evaluated:

    • null or undefined
    • boolean values (true or false)
    • number with length <= 6
    • string with length <= 6
  2. Exported TypeScript enums that collected by builtin:swc-loader collectTypeScriptInfo.exportedEnum

This optimization helps reduce bundle size and can improve runtime performance.

A common use case is with constants.js files:

// constants.js
export const A = true;
export const B = 'hello';

// index.js
import { A, B } from './constants';
console.log(A ? 1 : 2);
console.log(B.length);

When inlineExports is enabled, constant values will be inlined at their usage sites:

// Bundled by Rspack: output.js
const __webpack_modules__ = {
  './index.js': () => {
    // Constants are inlined directly
    console.log(true ? 1 : 2);
    console.log('hello'.length);
    // If all exports from constants.js are inlined, the constants.js module
    // will be optimized away and won't appear in the final output
  },
};
Tip

Since this feature relies on module export usage information (optimization.usedExports), it is recommended to enable it only in production mode where usedExports is enabled by default.

TDZ behavior

Inlining constant exports from modules in circular dependencies may change code that would otherwise throw a temporal dead zone (TDZ) error so that it no longer throws. Most tools in the ecosystem generally do not preserve TDZ errors when optimizing; Rspack also follows this optimization-first behavior.

For more details, refer to the inline const example.

optimization.innerGraph

optimization.innerGraph tells Rspack whether to perform a more detailed analysis of variable assignments. This helps Rspack to identify unused module exports, thereby reducing the size of the bundled output.

For example:

import { value } from 'lib';

const value2 = value;

function f1() {
  console.log(value);
}

function f2() {
  console.log(value2);
}

Here we assign the value to value2. Both value2 and value are accessed within the functions f2 and f1 respectively, but the functions are not called, hence value2 and value are not actually used, thus the import of value can be removed.

optimization.mangleExports

optimization.mangleExports controls how export names are mangled.

The following values are supported:

optiondescription
'size'Use the shortest possible export names to reduce bundle size.
'deterministic'Use short and stable export names for better long-term cache stability. Enabled by default in production mode.
trueSame as 'deterministic'.
falseDisable export mangling and keep original export names. Enabled by default in development mode.

For example, with the following source code:

src/math.js
export const veryLongExportName = 1;

When mangleExports is disabled, the export name is preserved:

dist/main.js
__webpack_require__.d(__webpack_exports__, {
  veryLongExportName: () => veryLongExportName,
});

When mangleExports is set to 'size', the export name is shortened:

rspack.config.mjs
export default {
  optimization: {
    mangleExports: 'size',
  },
};
dist/main.js
__webpack_require__.d(__webpack_exports__, {
  a: () => veryLongExportName,
});

optimization.mergeDuplicateChunks

  • Type: boolean
  • Default:true

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

rspack.config.mjs
export default {
  optimization: {
    mergeDuplicateChunks: false,
  },
};

optimization.minimize

Whether to use the minimizer declared in optimization.minimizer to minimize the bundle.

rspack.config.mjs
export default {
  optimization: {
    minimize: true,
  },
};

optimization.minimizer

  • Type: ('...' | Plugin)[]
  • Default:[new SwcJsMinimizerRspackPlugin(), new LightningCssMinimizerRspackPlugin()]

Customize the minimizer. By default, rspack.SwcJsMinimizerRspackPlugin and rspack.LightningCssMinimizerRspackPlugin are used.

When optimization.minimizer is specified, the default minimizers will be disabled.

rspack.config.mjs
import TerserPlugin from 'terser-webpack-plugin';

export default {
  optimization: {
    minimizer: [new TerserPlugin()],
  },
};

Use Rspack's built-in minimizer with custom options:

rspack.config.mjs
import { rspack } from '@rspack/core';

export default {
  optimization: {
    // when `optimization.minimizer` is specified, the default minimizers are disabled by default
    // but you can use '...', it represents the default minimizers
    minimizer: [
      new rspack.SwcJsMinimizerRspackPlugin({
        minimizerOptions: {
          format: {
            comments: false,
          },
        },
      }),
      new rspack.LightningCssMinimizerRspackPlugin({
        minimizerOptions: {
          errorRecovery: false,
        },
      }),
    ],
  },
};

optimization.moduleIds

Tells Rspack which algorithm to use when generating module ids.

The following string values are supported:

optiondescription
naturalUse numeric ids in order of usage.
namedUse meaningful, easy-to-debug content as id.
deterministicUse the hashed module identifier as the id to benefit from long-term caching. By default a minimum length of 3 digits is used.
compact-hashedUse the shortest available prefix of a stable alphanumeric hash.
hashedUse hashed module identifiers as ids. Equivalent to using HashedModuleIdsPlugin with default options (md4, base64, 4 chars).
falseDisable Rspack's built-in module id algorithm, allowing a custom plugin to provide module ids.

We recommend using named in development and deterministic or compact-hashed in production.

Use process.env.NODE_ENV to determine the current environment:

rspack.config.mjs
const isDev = process.env.NODE_ENV === 'development';

export default {
  optimization: {
    moduleIds: isDev ? 'named' : 'deterministic',
  },
};

The compact-hashed option uses the shortest available prefix of a stable alphanumeric hash as the module id, balancing long-term caching, bundle size, and runtime performance.

Deprecated alias

compat-hashed was available in Rspack 2.2.0. It is deprecated and was renamed to compact-hashed in Rspack 2.2.1. It remains available as a compatibility alias.

Warning

compact-hashed module ids are case-sensitive and may contain uppercase letters. On case-insensitive file systems, avoid using [id] as the only distinguishing placeholder in Asset module filenames or WebAssembly module filenames. Prefer [contenthash], or include it alongside [id].

rspack.config.mjs
const isDev = process.env.NODE_ENV === 'development';

export default {
  optimization: {
    moduleIds: isDev ? 'named' : 'compact-hashed',
  },
};
Tip

The compact-hashed option is available in Rspack 2.2.1 and later.

optimization.nodeEnv

optimization.nodeEnv controls the value used to replace process.env.NODE_ENV at compile time. Rspack performs this replacement with DefinePlugin.

You can override the mode-dependent default with either of the following values:

  • Any string: replace process.env.NODE_ENV with the specified string.
  • false: disable the replacement and leave process.env.NODE_ENV unchanged.
rspack.config.mjs
export default {
  optimization: {
    nodeEnv: 'production',
  },
};

optimization.providedExports

  • Type: boolean
  • Default:true

After enabling, Rspack will analyze which exports the module provides, including re-exported modules. A warning or error will be issued when importing members that reference non-existent exports. By default, optimization.providedExports is enabled. This analysis will increase build time. You may consider disabling this configuration in development mode. Disabling it may lead to errors related to runtime circular dependencies as mentioned in the SideEffects section.

rspack.config.mjs
export default {
  optimization: {
    providedExports: false,
  },
};

optimization.realContentHash

Adds an additional hash compilation pass after the assets have been processed to get the correct asset content hashes. This feature will enable by default in production mode.

If realContentHash is set to false, internal data is used to calculate the hash and it can change when assets are identical in some cases.

rspack.config.mjs
export default {
  optimization: {
    realContentHash: true,
  },
};

optimization.removeEmptyChunks

  • Type: boolean
  • Default:true

Detect and remove empty chunks generated in the compilation. Setting optimization.removeEmptyChunks to false will disable this optimization.

rspack.config.mjs
export default {
  optimization: {
    removeEmptyChunks: false,
  },
};

optimization.runtimeChunk

  • Type: boolean | 'single' | 'multiple' | { name?: string | ((entrypoint: { name: string }) => string) }
  • Default:false

Controls whether the Rspack runtime is extracted into separate chunks.

Defaults to false, which means the Rspack runtime code is inlined into the entry chunks.

Setting it to true or 'multiple' will add an additional chunk containing only the Rspack runtime for each entry point. This setting is an alias for:

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

Setting it to 'single' will extract the Rspack runtime code of all entry points into a single separate chunk named runtime. This setting is an alias for:

rspack.config.mjs
export default {
  optimization: {
    runtimeChunk: {
      name: 'runtime',
    },
  },
};

When optimization.runtimeChunk is an object, its optional name property controls the names of the Rspack runtime chunks.

rspack.config.mjs
export default {
  optimization: {
    runtimeChunk: {
      // this will generate a chunk named `my-name.js`
      name: 'my-name',
    },
  },
};
Tip

Each Rspack runtime initializes imported modules separately. If multiple entries on the same page need to share module instances, set optimization.runtimeChunk to 'single' or use another configuration that lets them share one runtime instance.

The following configuration defines two entries, pageA and pageB. Suppose both entry files import the same shared.js module, and their generated bundles are loaded on the same HTML page:

rspack.config.mjs
export default {
  entry: {
    pageA: './src/page-a.js',
    pageB: './src/page-b.js',
  },
  optimization: {
    runtimeChunk: 'single',
  },
};

Changing runtimeChunk affects the output files and how often shared.js is initialized:

runtimeChunkGenerated JavaScript filesshared.js initializations
falsepageA.js, pageB.jsTwice
'multiple'runtime~pageA.js, runtime~pageB.js, pageA.js, pageB.jsTwice
'single'runtime.js, pageA.js, pageB.jsOnce

When writing HTML manually, place the runtime file's <script> tag before the entry bundles' tags. HtmlRspackPlugin handles this order automatically. With 'single', both entries share one Rspack runtime and its module cache, so shared.js is initialized only once.

Sharing a Rspack runtime does not extract shared modules into a separate file. Use SplitChunksPlugin to configure module splitting.

optimization.sideEffects

If you only want Rspack use the manual sideEffects flag via (package.json and rules[].sideEffects) and don't analyse source code:

rspack.config.mjs
export default {
  optimization: {
    sideEffects: 'flag',
  },
};

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

true tells Rspack not only recognise the sideEffects flag, but also analyse modules which are not flagged explicitly, and determine if they have side effects or not.

rspack.config.mjs
export default {
  optimization: {
    sideEffects: true,
  },
};
Tip

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.

optimization.splitChunks

  • Type: false | object

Rspack supports splitting chunks with the optimization.splitChunks configuration item.

It is enabled by default for dynamically imported modules.

To turn it off, set it to false.

See available options for configuring this behavior in the SplitChunksPlugin page.

optimization.usedExports

Tells Rspack 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.

rspack.config.mjs
export default {
  optimization: {
    usedExports: false,
  },
};

To analyze used exports globally instead of separately for each Rspack runtime:

rspack.config.mjs
export default {
  optimization: {
    usedExports: 'global',
  },
};

This page is adapted from webpack documentation under the CC BY 4.0, with modifications.