Back to Rspack

TreeShakingSharedPlugin

website/docs/en/plugins/webpack/tree-shaking-shared-plugin.mdx

2.1.91.5 KB
Original Source

import { Stability, ApiMeta } from '@components/ApiMeta';

TreeShakingSharedPlugin

<ApiMeta stability={Stability.Experimental} />

Overview

  • Performs on-demand build and export optimization for shared dependencies based on Module Federation configuration.

Options

  • mfConfig: ModuleFederationPluginOptions, configuration passed to the Module Federation plugin.
  • secondary: whether to perform a second tree-shake during independent builds (typically used when the deployment platform has determined complete dependency info and triggers a fresh build to improve tree-shake accuracy for shared dependencies).

Usage

js
import { sharing } from '@rspack/core';

export default {
  plugins: [
    new sharing.TreeShakingSharedPlugin({
      secondary: true,
      mfConfig: {
        name: 'app',
        shared: {
          'lodash-es': { treeShaking: { mode: 'server-calc' } },
        },
        library: { type: 'var', name: 'App' },
        manifest: true,
      },
    }),
  ],
};

Behavior

  • Normalizes shared into [shareName, SharedConfig][].
  • Registers SharedUsedExportsOptimizerPlugin when secondary is false to inject used-exports from the stats manifest.
  • Creates an independent build only for shared dependencies that enable treeShaking and retain a local implementation (that is, import is not false).
  • When mfConfig.manifest is enabled, records the independent build output in the stats and manifest files so the runtime can load it as a fallback.