Vite配置详解

时游大约 1 分钟

Vite 配置详解(vite.config.ts)

配置文件结构

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "node:url";

export default defineConfig({
	plugins: [vue()],
	resolve: {
		// 路径别名:@ 指向 src 目录
		alias: {
			"@": fileURLToPath(new URL("./src", import.meta.url))
		},
		// 引入依赖时可省略的后缀(默认已含 .ts/.js/.vue 等)
		extensions: [".ts", ".js", ".vue"]
	},
	server: {
		host: "0.0.0.0", // 监听所有地址,局域网可访问
		port: 20777, // 端口号
		open: true, // 启动后自动打开浏览器
		proxy: {
			// 接口代理,解决开发环境跨域
			"/api": {
				target: "http://localhost:3000",
				changeOrigin: true,
				rewrite: path => path.replace(/^\/api/, "") // 去掉 /api 前缀
			}
		}
	},
	css: {
		preprocessorOptions: {
			scss: {
				additionalData: `@use "@/styles/variables.scss" as *;` // 全局注入 scss 变量
			}
		}
	}
});

按环境区分配置

# .env                # 所有环境都加载
# .env.development    # npm run dev 时加载
# .env.production     # npm run build 时加载
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
	// mode 为 'development' | 'production',加载对应 env 文件
	const env = loadEnv(mode, process.cwd());
	console.log(env.VITE_API_URL);

	return {
		// 也可以按 mode 返回不同配置
	};
});

条件插件

export default defineConfig(({ command }) => ({
	plugins: [
		vue(),
		// 仅在 build 时启用压缩分析
		command === "build" && visualizer()
	]
}));

常用插件

插件作用
@vitejs/plugin-vueVue3 单文件组件支持(官方)
@vitejs/plugin-vue-jsxJSX/TSX 支持
@vitejs/plugin-legacy为旧浏览器生成 polyfill 包
unplugin-auto-import自动导入 api(ref、computed 等)
unplugin-vue-components组件自动按需注册
vite-plugin-compression构建时生成 gzip 压缩文件
rollup-plugin-visualizer打包体积可视化分析
vite-plugin-svg-iconssvg 雪碧图

其他实用配置

export default defineConfig({
	// 依赖预构建
	optimizeDeps: {
		include: ["lodash-es"] // 提前预构建,避免运行时重复触发
	},
	// 构建输出
	build: {
		outDir: "dist",
		sourcemap: false,
		// 分包策略
		rollupOptions: {
			output: {
				manualChunks: {
					vendor: ["vue", "vue-router", "pinia"],
					echarts: ["echarts"]
				}
			}
		}
	}
});
Loading...