用途
该技能用于减小使用 Ignite UI Web Components 的应用打包体积。当用户反馈 bundle 过大、想为生产环境做优化、导入的组件多于实际需要,或询问 tree-shaking、加载速度时适用。
主要原则
- 只导入用到的组件,不使用 defineAllComponents()。
- 使用具名导入,以便启用 tree-shaking。
- 分析 bundle 内容,确认其中包含哪些模块。
- 在可能的情况下懒加载组件。
- 若应用只使用一个主题,设置 igc-theme-<name> 条件。
导入策略
不推荐写法会导入全部 60+ 组件(约 500KB+):
import { defineAllComponents } from 'igniteui-webcomponents';
defineAllComponents();
推荐按需导入:
import {
defineComponents,
IgcButtonComponent,
IgcInputComponent,
IgcCardComponent
} from 'igniteui-webcomponents';
defineComponents(IgcButtonComponent, IgcInputComponent, IgcCardComponent);
React 项目可改用 igniteui-react 包(npm install igniteui-react),组件会自动注册,通常 tree-shaking 效果更好。
使用方式
- 用分析工具检查 bundle:Vite 用 rollup-plugin-visualizer,Webpack 用 webpack-bundle-analyzer,跨框架可用 source-map-explorer。
- 用 grep 搜索代码中的 igc- 标签,列出实际使用的组件,并与导入清单对比,删除未使用的导入。
- 对对话框等低频组件使用动态 import 懒加载;也可按路由拆分,把 defineComponents(...) 放在懒加载的路由模块中。文档给出了原生 JS/TS、React、Vue 3、Angular 的写法示例。
- 构建配置:确保生产模式与压缩开启;Vite 可调整 chunkSizeWarningLimit,Webpack 可用 splitChunks 把 igniteui-* 放入独立 vendor chunk。
只打包单一主题
组件默认携带 Material、Bootstrap、Indigo、Fluent 四套主题样式。若只用一套,可在打包器中设置条件:
- Vite:resolve: { conditions: ['igc-theme-bootstrap', ...defaultClientConditions] }(SSR 还需设置 ssr.resolve.conditions)
- webpack:resolve: { conditionNames: ['igc-theme-bootstrap', '...'] }
- esbuild:conditions: ['igc-theme-bootstrap']
- Rollup:nodeResolve({ exportConditions: ['igc-theme-bootstrap'] })
- Node.js SSR:node --conditions=igc-theme-bootstrap server.js
可用条件为 igc-theme-material、igc-theme-bootstrap、igc-theme-indigo、igc-theme-fluent,只能设置一个。仅当应用不通过 configureTheme() 切换其他主题时使用;未打包的主题只提供结构样式。全局主题 CSS 仍需单独加载。igniteui-react 同样适用。据文档,单主题可使 gzip 后体积约减小 15%–17%。
适用场景与限制
适用于基于 Ignite UI Web Components 的前端应用体积优化与生产构建调优。实际体积取决于导入的组件,Grid、Chart 等组件明显大于普通 UI 组件,应以分析工具实测为准,不要依赖通用估算。常见问题包括:优化后 bundle 仍大(检查导入数量、tree-shaking、重复依赖、source map、React 是否误用 webcomponents 包)、优化后组件不工作(漏导入对应组件)、TypeScript 报错(单独用 import type 导入类型)。还可在 CI 中用 bundlesize、size-limit、Bundlewatch 设置体积上限进行持续监控。