从带pages的vue.config.js迁移至vite.config.js的配置咨询
Vue2迁移Vue3 + Vite替代Webpack:代码分割与Tree Shaking配置方案
一、提取chunk-vendors与chunk-common
Vite基于Rollup,直接在vite.config.js的build.rollupOptions.output里配置代码分割规则,对应Webpack的splitChunks逻辑。
1. 手动指定模块的配置示例
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname, 'src') // 和原vue.config.js保持一致的别名配置 } }, build: { rollupOptions: { output: { // 手动指定代码分割规则 manualChunks: { // 把第三方依赖打包到chunk-vendors 'chunk-vendors': ['vue', 'vue-router', 'axios', 'element-plus'], // 替换成你的项目依赖 // 把复用率高的自有模块打包到chunk-common 'chunk-common': ['@/utils/common', '@/components/BaseButton', '@/components/BaseTable'] }, // 保持chunk命名规则和Webpack一致,减少迁移后的资源引用改动 chunkFileNames: 'js/[name]-[hash].js', entryFileNames: 'js/[name]-[hash].js', assetFileNames: '[ext]/[name]-[hash].[ext]' } } } })
2. 自动识别共享模块(无需手动列模块)
如果不想逐个指定共享模块,可用函数版manualChunks自动拆分:
manualChunks(id) { // 第三方依赖统一打包到chunk-vendors if (id.includes('node_modules')) { return 'chunk-vendors' } // 自有代码中,utils、components下的模块被多页面引用时,打包到chunk-common const sharedDirs = ['@/utils', '@/components'] for (const dir of sharedDirs) { if (id.includes(dir)) { return 'chunk-common' } } }
二、确保Tree Shaking生效
Vite生产构建默认开启Tree Shaking,只需注意几个关键点:
- 项目代码全部用ES模块语法(
import/export),避免使用CommonJS的require,后者会影响Tree Shaking效果 - 在
package.json中声明副作用文件,让Rollup更精准地摇树:
{ "sideEffects": [ "*.css", "*.scss", "./src/utils/global-init.js" // 有全局副作用的文件单独列出来 ] }
- 如需更严格的摇树规则,可在rollupOptions中补充:
build: { rollupOptions: { treeshake: { moduleSideEffects: 'no-external', // 认为外部依赖无副作用 propertyReadSideEffects: false, // 属性读取无副作用 tryCatchDeoptimization: false // 关闭try/catch场景下的摇树降级 } } }
三、对应Webpack configureWebpack的配置对照
原vue.config.js中configureWebpack的代码分割配置通常是这样:
// 原vue.config.js的configureWebpack片段 module.exports = { configureWebpack: { optimization: { splitChunks: { chunks: 'all', cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, name: 'chunk-vendors', priority: -10 }, common: { name: 'chunk-common', minChunks: 2, // 被至少2个入口引用才拆分 priority: -20, reuseExistingChunk: true } } } } } }
在Vite中,上述cacheGroups的逻辑完全可以通过前面的manualChunks函数实现,自动识别共享模块的写法和Webpack的common缓存组逻辑一致。
四、多页面pages配置迁移
如果原项目是多页面架构,Vite中需要手动配置入口文件,对应原vue.config.js的pages配置:
export default defineConfig({ build: { rollupOptions: { input: { index: resolve(__dirname, 'src/pages/index/index.html'), admin: resolve(__dirname, 'src/pages/admin/index.html') // 按原pages配置逐个添加入口 } } } })
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

