You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Vite减少JavaScript Chunks数量并解决加载异常?

解决Vite生成大量极小Chunks的问题

针对Vite构建后出现大量小于1KB的极小Chunk(同时存在少数超大Chunk)、导致页面加载异常的问题,可以通过以下几种方式优化:

1. 自定义Rollup的manualChunks合并模块

通过手动指定chunk分组,将第三方依赖、项目内的小模块合并到统一的chunk中,减少碎片化。修改Vite配置中的rollupOptions.output:

rollupOptions: {
  output: {
    chunkFileNames: 'chunk-[name].[hash].js',
    entryFileNames: 'entry-[name].[hash].js',
    inlineDynamicImports: false,
    sourcemap: true,
    // 添加manualChunks配置
    manualChunks: {
      // 把所有第三方依赖打包到vendor chunk
      vendor: ['react', 'react-dom', 'styled-components', 'relay-runtime'],
      // 把项目内工具类、通用组件等合并到utils chunk
      utils: ['@/utils', '@/hooks', '@/constants', '@/components/shared']
    }
  }
}

也可以用函数方式动态分组,更灵活:

manualChunks(id) {
  // 第三方依赖统一合并
  if (id.includes('node_modules')) {
    return 'vendor';
  }
  // 项目内components目录下的小文件合并到shared-components
  if (id.includes('src/components') && id.endsWith('.jsx')) {
    return 'shared-components';
  }
}

2. 设置Rollup的minChunkSize强制合并小Chunk

通过minChunkSize配置,自动合并小于指定大小的Chunk,直接减少小Chunk数量:

rollupOptions: {
  output: {
    // 原有配置...
    minChunkSize: 10 * 1024 // 合并小于10KB的Chunk
  }
}

3. 优化动态导入的使用

项目中大量分散的动态导入是生成小Chunk的常见原因,可通过以下方式优化:

  • 将多个小组件/模块统一导出后再动态导入,避免单独拆分:
    // 原写法(每个组件生成独立Chunk)
    const Button = () => import('@/components/Button');
    const Input = () => import('@/components/Input');
    
    // 优化后(合并到同一个Chunk)
    const FormComponents = () => import('@/components/FormControls');
    // 在FormControls.jsx中统一导出Button、Input等组件
    
  • 使用webpackChunkName注释强制合并相关动态导入:
    const Button = () => import(/* webpackChunkName: "form-components" */ '@/components/Button');
    const Input = () => import(/* webpackChunkName: "form-components" */ '@/components/Input');
    

4. 排查vite-plugin-ssr的拆分策略

由于使用了vite-plugin-ssr,需检查插件文档中是否有页面Chunk拆分的相关配置:

  • 是否开启了按页面独立拆分Chunk的选项,可调整为合并页面公共依赖;
  • 是否有控制Chunk粒度的参数,降低过度拆分的程度。

5. 排查第三方插件的影响

暂时禁用babel-plugin-relay、babel-plugin-styled-components等插件,测试是否是插件导致的过度拆分。若确认是某插件问题,可查看插件文档调整配置,或寻找替代方案。

内容的提问来源于stack exchange,提问作者Gajus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:03:23