构建出现问题——点开日志——完整版——搜索error——定位问题
error ❌入口文件体积过大,你的罪行已被记录,请立刻优化代码。以下文件超过 2mb(压缩前):vendor.js: 3124KB
at /cloud/source_code/apps/portal/plugins/rsbuildPluginDistCheck.ts:35:17
好的,现在明确了问题:
这是一个前端打包优化问题,vendor.js 文件大小超过了 2MB 的限制(3124KB)。这是典型的 bundle 体积过大问题。
原因是:
在代码/apps/portal/plugins/rsbuildPluginDistCheck.ts中 Rsbuild 构建工具中自定义了一个体积检查插件,这个插件报的异常,阻止了构建完成✅。
临时解决方案:
1、在 rsbuild.config.ts 中注释掉该插件
2、在自定义插件中将体积限制从 2MB 调整为 3MB 或 3.5MB
长期方案:
1、分析
(1)使用打包分析工具查看哪些包占用空间最大
# 安装 webpack-bundle-analyzer
pnpm add -D webpack-bundle-analyzer
# 或使用 vite-bundle-analyzer (如果项目使用 Vite)
pnpm add -D rollup-plugin-visualizer
# 在构建配置中添加分析插件
(2)检查大型依赖
# 检查 node_modules 大小
du -sh node_modules
# 检查具体包的大小
pnpm list --depth=0
2、代码分割优化
(1) 将大型依赖单独拆分,或者使用函数形式进行更精细的控制, 将其他 node_modules 打包到 vendor 中
// vite.config.ts 示例
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
// 将大型依赖单独拆分
'react-vendor': ['react', 'react-dom'],
'antd-vendor': ['antd'],
'utils-vendor': ['lodash', 'moment'], // 如果有使用
},
// 或者使用函数形式进行更精细的控制
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('antd')) {
return 'antd';
}
if (id.includes('@ant-design')) {
return 'ant-design';
}
if (id.includes('lodash') || id.includes('moment')) {
return 'utils';
}
// 将其他 node_modules 打包到 vendor 中
return 'vendor';
}
}
}
}
}
});
// 在您的 rsbuild.config.ts 中,修改 cacheGroups
cacheGroups: {
// 禁用默认的 default 规则
default: false,
// 将大型库单独拆分
reactVendor: {
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
name: 'react-vendor',
chunks: 'initial',
priority: 30,
enforce: true,
},
antdVendor: {
test: /[\\/]node_modules[\\/](antd|@ant-design)[\\/]/,
name: 'antd-vendor',
chunks: 'initial',
priority: 25,
enforce: true,
},
// 将其他 node_modules 代码按大小拆分,而不是全部放入 vendor
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'initial',
priority: 10,
minSize: 100 * 1024, // 只有大于 100KB 的包才会单独拆分
},
},
(2)对于不需要立即加载的组件,使用动态导入
// 优化 ScheduleCard 中的导入(如果适用)
const LazyComponent = lazy(() => import('./SomeLargeComponent'));
(3) Ant Design 等大型库按需加载
# 安装按需加载插件
pnpm add -D babel-plugin-import # 如果使用 Babel
# 或
pnpm add -D unplugin-auto-import unplugin-vue-components # 如果使用 Vite
(4)检查移除未使用的依赖
# 检查未使用的包
pnpm dlx depcheck
# 移除不需要的依赖
pnpm remove [package-name]
(5) 配置 Tree Shaking
// vite.config.ts
export default defineConfig({
build: {
rollupOptions: {
treeshake: true,
output: {
// 确保保留注释中的 license 信息
banner: '',
}
}
}
});
(6)对于大型库,确保只导入需要的部分
// ❌ 错误 - 导入整个库
import * as _ from 'lodash';
// ✅ 正确 - 按需导入
import debounce from 'lodash/debounce';