Vite
1.安装一些性能优化相关的包
npm i terser -D
2.构建优化配置
import { defineConfig, loadEnv } from "vite";
import { resolve } from "path";
export default defineConfig(({ mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd(), "");
// 根据环境变量设置 base
const base = mode === "production" ? "" : "/qinyaohui/dev/quilljs/";
return {
base: base,
// 开发服务器优化
server: {
// 自动打开浏览器
open: true,
// 启用热更新
hmr: true,
// 服务器端口
port: 8080,
// 允许外部访问
host: "0.0.0.0",
// 启用预构建优化
force: false,
// 启用压缩,这个压缩只会影响到开发服务器的行为,不会修改我的源代码
compress: true,
},
// 构建优化
build: {
// 设置构建目标,支持现代浏览器
target: "es2015",
// 启用源码映射(生产环境建议关闭)
sourcemap: mode === "development",
// 设置输出目录
outDir: "dist",
// 启用 CSS 代码分割
cssCodeSplit: true,
// 启用 CSS 压缩
cssMinify: true,
// 设置chunk大小警告限制
chunkSizeWarningLimit: 1000,
// 启用 gzip 压缩
reportCompressedSize: true,
// 启动压缩html和js
minify: "terser",
//压缩选项
terserOptions: {
compress: {
//开发环境移除console和debugger
drop_console: mode === "production",
drop_debugger: mode === "production",
passes: 2, // 多次压缩,提高压缩效果
dead_code: true, // 移除死代码
},
mangle: {
// 混淆变量名 - 将长变量名替换为短变量名
toplevel: true, // 混淆顶级变量名
eval: true, // 混淆 eval 中的变量
keep_fnames: false, // 不保留函数名
// 自定义混淆规则
reserved: ['$', 'jQuery'], // 保留某些变量名不被混淆
},
format: {
// 格式化选项
comments: false, // 移除注释
beautify: false, // 不美化代码
indent_level: 0, // 缩进级别
},
},
// 启动rollup选项,html压缩配置
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
},
output: {
// 手动代码分割
manualChunks: {
// 第三方库单独打包
vendor: ["quill", "quill-mention"],
// 工具库单独打包
utils: ["axios"],
},
// 设置chunk文件名格式
chunkFileNames: "assets/js/[name]-[hash].js",
// 设置入口文件名格式
entryFileNames: "assets/js/[name]-[hash].js",
// 设置资源文件名格式
assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
},
},
},
// 依赖预 构建配置 - 智能优化开发体验, 通常开发中不使用这个配置项
optimizeDeps: {
// 预构建包含的依赖 - 通常不需要手动配置,Vite 会自动检测
// 只在以下情况手动配置:
// 1. 某些库预构建失败
// 2. 需要强制预构建特定库
// 3. 性能优化需求
include: [
// 常用第三方库
"quill",
"quill-mention",
"axios",
// 如果使用 Vue
// "vue", "vue-router", "pinia",
// 如果使用 React
// "react", "react-dom", "react-router-dom",
// 如果使用 UI 库
// "element-plus", "ant-design-vue", "vant",
],
// 排除不需要预构建的依赖
exclude: [
// 排除有问题的依赖
"@tailwindcss/oxide",
"@tailwindcss/node",
"@tailwindcss/vite",
],
// 强制预构建 - 开发时遇到问题可以设置为 true
force: false,
// 预构建选项
esbuildOptions: {
target: "es2015", // 预构建目标
},
// 预构建缓存目录
cacheDir: "node_modules/.vite",
// 预构建日志
logLevel: "info",
},
// 解析配置
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
// 文件扩展名解析,简化导入语句,如只需import LoginPage from "@/LoginPage"不需要后缀
extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json",'vue'],
},
// 插件配置
plugins: [],
};
});