vite: split chunks(分片)

工作中常用的将项目文件分片场景

01 安装插件

注意,这一步其实是提醒,不需要安装任何的插件

02 配置 vite.config.ts

示例配置文件,重点关注这个路径: build.rollupOptions.output.manualChunks 这一行的配置

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: '0.0.0.0'
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            if (id.includes('@jswork')) return 'jswork';
            return id.toString().split('node_modules/')[1].split('/')[0];
          }
        }
      }
    }
  }
});

03 常用配置参考 cheatsheet

常用配置

场景代码
公司项目
rollupOptions: {
  output: {
    manualChunks: {
      'react': ['react'],
      'react-dom': ['react-dom'],
      'react-router-dom': ['react-router-dom'],
      'lodash': ['lodash'],
      'marked': ['marked'],
      'dayjs': ['dayjs'],
      'html2canvas': ['html2canvas'],
      'framer-motion': ['framer-motion'],
      'qrcode-react': ['qrcode.react'],
      'mantine-core': [
        "@mantine/core",
        "@mantine/hooks",
      ],
      'mantine-extensions': [
        "@mantine/carousel",
        "@mantine/dates",
        "@mantine/dropzone",
        "@mantine/form",
        "@mantine/modals",
        "@mantine/notifications"
      ],
    }
  }
}
简单项目
rollupOptions: {
  output: {
    manualChunks(id) {
      if (id.includes('node_modules')) {
        if (id.includes('@jswork')) return 'jswork';
        return id.toString().split('node_modules/')[1].split('/')[0];
      }
    }
  }
}
其它
rollupOptions: {
  output: {
    manualChunks: (id) => {
      // List of modules that rollup sometimes bundles with manual chunks
      // causing those chunks to be eager-loaded
      const ROLLUP_COMMON_MODULES = [
        "vite/preload-helper",
        "vite/modulepreload-polyfill",
        "vite/dynamic-import-helper",
        "commonjsHelpers",
        "commonjs-dynamic-modules",
        "__vite-browser-external",
      ];

      // Split out mock code into its own chunk
      // (THIS IS AN EXAMPLE, REPLACE WITH WHATEVER YOU NEED)
      if (id.includes("/node_modules/@mswjs/")) {
        return "mock";
      }

      // Bundle all other 3rd-party modules into a single vendor.js module
      if (
        id.includes("node_modules") ||
        ROLLUP_COMMON_MODULES.some((commonModule) => id.includes(commonModule))
      ) {
        return "vendor";
      }

      // All other files are project source files and are allowed to be
      // split whichever way rollup wants
    };
  }
}
vite rollup manualChunks