vite-plugin-chunk-split

repository·master·Indexed 19 days ago

https://github.com/sanyuan0704/vite-plugin-chunk-split

A Vite plugin for granular and customizable control over code chunk splitting during the build process. It supports multiple strategies including 'default', 'all-in-one', and 'unbundle' for bundleless architectures. Users can define custom splitting rules via the customSplitting option using package names or regular expressions, or implement a customChunk function for programmatic control over chunk assignment.

Tokens
2.8K
Snippets
11
Records
13
Agent score
61%

What's inside vite-plugin-chunk-split

  1. Define custom splitting rules with customSplitting

    master

    Use the customSplitting option to group specific packages or file patterns into named chunks. The key is the chunk name, and the value is an array of packageInfo (which can be a string for package names or a RegExp for file paths).

    Example configurations:

    • 'react-vendor': ['react', 'react-dom'] bundles React and React-DOM together.
    • 'utils': [/src\/utils/] bundles any file matching the regex into a utils chunk.
    // vite.config.ts
    import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
    
    export default {
      plugins: [
        chunkSplitPlugin({
          customSplitting: {
            // Bundles react and react-dom together
            'react-vendor': ['react', 'react-dom'],
            // Bundles any file in src/utils using a regex
            'utils': [/src\/utils/]
          }
        })
      ]
    }
  2. Configure chunk splitting strategies and custom splitting

    master

    You can fine-tune the chunking behavior using the ChunkSplitOptions object. This allows you to define a global strategy and specific customSplitting rules.

    Strategies

    • 'default': The default splitting behavior.
    • 'all-in-one': Bundles all files together into a single chunk.
    • 'unbundle': Implements a bundleless approach where each file is its own chunk (unless specified otherwise in customSplitting).

    Custom Splitting

    The customSplitting option is a Record<string, packageInfo[]> where:

    • The key is the name of the resulting chunk.
    • The value is an array of packageInfo (either a string for package names or a RegExp for file paths) that should be included in that chunk.

    Example: Grouping React dependencies and specific source directories.

    // vite.config.ts
    import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
    
    export default {
      plugins: [
        chunkSplitPlugin({
          strategy: 'default',
          customSplitting: {
            // 'react' and 'react-dom' will be bundled into a chunk named 'react-vendor'
            'react-vendor': ['react', 'react-dom'],
            // All code in the src/utils directory will be bundled into the 'utils' chunk
            'utils': [/src\/utils/]
          }
        })
      ]
    }
  3. Configure chunk splitting strategies

    master

    The strategy option determines the high-level approach to chunking. Available strategies are:

    • 'default': The default splitting behavior.
    • 'all-in-one': Bundles all files together into a single chunk.
    • 'unbundle': Unbundles source files, causing Vite to generate one chunk for every file. This can be used to achieve a bundleless architecture while still allowing specific groups of files to be merged via customSplitting.
  4. Achieve bundleless mode with the unbundle strategy

    master

    To achieve a bundleless setup where Vite generates individual chunks for files, set the strategy to 'unbundle'. You can still use customSplitting to merge specific directories or patterns into shared chunks.

    // vite.config.ts
    import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
    
    export default {
      plugins: [
        chunkSplitPlugin({
          strategy: 'unbundle',
          customSplitting: {
            // All files in `src/container` will be merged together in the `container` chunk
            'container': [/src\/container/]
          }
        })
      ]
    }
  5. Implement bundleless mode with custom grouping

    master

    To achieve a bundleless (unbundle) setup while still merging specific files into groups, set the strategy to 'unbundle' and use customSplitting to define your groups.

    Example: Merging all files under src/container into a single chunk named container while keeping other files separate.

    // vite.config.ts
    import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
    
    export default {
      plugins: [
        chunkSplitPlugin({
          strategy: 'unbundle',
          customSplitting: {
            // All files under src/container will be merged into one chunk named 'container'
            'container': [/src\/container/]
          }
        })
      ]
    }
  6. Reference ChunkSplitOptions type

    master

    The configuration interface for the plugin.

    type packageInfo = string | RegExp;
    type Strategy =
      // Default splitting
      | 'default'
      // All files bundled together
      | 'all-in-one'
      // Bundleless: one file per chunk
      | 'unbundle';
    
    export type CustomSplitting = Record<string, packageInfo[]>;
    
    export interface ChunkSplitOptions {
      strategy?: Strategy;
      customSplitting?: CustomSplitting;
    }
  7. Configure vite-plugin-chunk-split options

    master

    The ChunkSplit interface defines the configuration options for the plugin. You can control how chunks are split using a predefined strategy, custom grouping via customSplitting, or fine-grained control with a customChunk function.

    import { ChunkSplit } from 'vite-plugin-chunk-split';
    
    const options: ChunkSplit = {
      strategy: 'single-vendor',
      customSplitting: {
        'my-group': ['lodash', /@mui\/.*/],
      },
      useEntryName: true,
    };
  8. Implement a custom chunk function

    master

    The customChunk option provides a callback to manually determine the chunk name for any given module. This gives you full control over the output filenames based on the module's context.

    const customChunk: (context: {id:string, moduleId:string, file:string, root:string}) => string | undefined | null = (context) => {
      if (context.moduleId.includes('special-module')) {
        return 'special-chunk';
      }
      return undefined;
    };
  9. Use chunkSplitPlugin to configure chunk splitting

    master

    The chunkSplitPlugin is a Vite plugin used to manage how Rollup splits code into chunks during the build process. It allows you to define strategies for grouping dependencies (like node_modules) or specific modules into named chunks.

    Configuration Options

    The plugin accepts a ChunkSplit object with the following properties:

    • strategy: Determines the splitting logic. Supported values are:
      • "default": (Default) Groups node_modules into chunks based on their entry names. Static imports from node_modules are treated as part of the entry chunk unless specified otherwise.
      • "unbundle": Splits node_modules into vendor (for statically imported modules) and async-vendor (for dynamically imported modules). It also attempts to create chunks for local files based on their relative path.
      • "all-in-one": Minimizes chunk splitting by effectively bypassing the default manual chunking logic, primarily relying on customSplitting and customChunk.
    • useEntryName: (Boolean, default: true) When using the default strategy, if true, node_modules are assigned chunks based on their entry names. If false, they are grouped into a single "vendor" chunk.
    • customSplitting: An object used to define custom groups. Keys are chunk names, and values are arrays of strings (package paths) or Regular Expressions to match module IDs.
    • customChunk: A function (options) => string | null that allows for fine-grained, programmatic control over chunk assignment for any module ID.
    import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
    
    export default defineConfig({
      plugins: [
        chunkSplitPlugin({
          strategy: 'unbundle',
          customSplitting: {
            'react-vendor': ['react', 'react-dom'],
            'utils-vendor': [/lodash/, /underscore/],
          },
        }),
      ],
    });
  10. Define custom splitting groups

    master

    The customSplitting option allows you to group specific packages or modules into named chunks. The value is a record where the key is the chunk name and the value is an array of packageInfo.

    packageInfo can be a string (exact package name) or a RegExp (to match module paths).

    const customSplitting: Record<string, (string | RegExp)[]> = {
      'react-vendor': ['react', 'react-dom'],
      'ui-library': [/^@mui\//],
    };