背景
公司将统一用户中心提取为 两个模块的组件User Permissions和 User information提取为 npm包。供给公司其他部门进行统一用户中心登录。本次主要说明下优化包的体积过大问题
1.历史版本对比:
| 包名 | 版本 | 体积 | 图片 |
|---|---|---|---|
| permission | 0.0.20 | 11.8MB | |
| - | 0.0.30 | 1.68MB | |
| - | 0.0.34 | 387kb |
2.优化点:
-
从删除无用的文件以及无用的函数方法开始,前后一共删除大约705个文件。
-
依赖外部引入(最重要的一步)。
- 关闭sourcemap。
- 使用代码压缩工具。
- 将react、react-dom、axios、antd、ant-design-pro等依赖排除不打入最终的包内。
-
// vite.config.ts defineConfig({ //... build: { sourcemap: false, // 一定要关闭 sourcemap // reportCompressedSize: false, minify: 'terser', // 使用代码压缩工具 terserOptions: { // 去掉console和debugger compress: { drop_console: true, drop_debugger: true, }, }, outDir: 'lib', // 组件库输出文件夹 cssTarget: 'chrome61', lib: { // 组件库源码的入口文件 entry: resolve('src/permission.ts'), // 组件库名称 name: 'permission', // 文件名称, 打包结果举例: my-packages.umd.cjs fileName: 'permission', }, rollupOptions: { // 本组件库不想导入最终产物的依赖,再此处忽略。 external: [ 'react', 'react-dom', 'react-router', 'react-router-dom', 'antd', '@ant-design/icons', '@ant-design/pro-components', 'axios', 'dayjs', ], output: { // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量 globals: { react: 'react', 'react-dom': 'react-dom', 'react-router': 'react-router', 'react-router-dom': 'react-router-dom', antd: 'antd', '@ant-design/icons': 'icons', '@ant-design/pro-components': 'ProComponents', axios: 'axios', dayjs: 'dayjs', }, }, }, }, // ... })
这段配置中的 rollupOptions 控制了 Rollup 打包器的行为,具体来说:
external: 这里列出了组件库不想在最终产物中打包的外部依赖项。当 Rollup 打包时,它将会忽略这些依赖,而不是将它们打包到最终的输出文件中。在这个示例中,列出了一些常见的依赖,如 React、Ant Design、Axios 等。这样做的好处是可以减小最终打包文件的大小,同时也能够避免在组件库使用者的项目中重复引入这些依赖。output: 这里设置了在 UMD 构建模式下为外部化的依赖提供一个全局变量。这是为了确保在使用组件库时,这些依赖项可以正确地被全局访问到。例如,如果在项目中引入了组件库,并且项目本身没有直接引入 React,但是组件库中使用了 React,那么需要确保组件库中的 React 可以正确地被项目访问到。通过在globals中指定这些依赖的全局变量名,可以确保它们在使用时被正确地解析和访问。
-
清除没有使用到的三方插件,共清除14个无用的第三方依赖,注意:如果三方插件用到的功能比较少,尽量自己实现,比如loadsh只是用到了深拷贝/防抖/截流。
-
在 package.json 中,如果你的库或插件依赖于某些特定版本的其他库,但又不希望将这些库打包到你的插件或库中,你可以将它们声明为 peer dependencies(对等依赖关系)。
"peerDependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"axios": "^1.5.1",
"dayjs": "^1.11.10",
"react-router": "^6.17.0",
"react-router-dom": "^6.17.0",
"antd": "^5.11.0",
"@ant-design/icons": "^5.2.6"
}