javascript
复制代码
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import vueDevTools from "vite-plugin-vue-devtools";
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
const isProduction = mode === "prod";
return {
plugins: [
vue(),
// 仅在生产环境外启用 devtools
!isProduction && vueDevTools(),
].filter(Boolean),
optimizeDeps: {
include: ["wangeditor"],
},
base: "/",
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
// 仅生产环境 移除 console 和 debugger
esbuild: {
drop: isProduction ? ["console", "debugger"] : [],
},
build: {
// 代码压缩配置 - 仅生产环境压缩,非生产环境不压缩便于调试
minify: isProduction ? "esbuild" : false,
// 调试模式 - 非生产环境生成 sourcemap
sourcemap: !isProduction,
// 代码分割策略
rollupOptions: {
output: {
// 手动分包配置
manualChunks: {
// Vue 核心库
"vue-vendor": ["vue", "vue-router", "pinia"],
// Element Plus
"element-plus": ["element-plus", "@element-plus/icons-vue"],
// Ant Design Vue
"ant-design-vue": ["ant-design-vue"],
// 工具库
utils: ["axios", "wangeditor"],
},
// 文件命名规则 - 添加 hash 用于缓存控制
chunkFileNames: "js/[name]-[hash].js",
entryFileNames: "js/[name]-[hash].js",
// CSS 文件输出到 css 目录
assetFileNames: (assetInfo) => {
// 判断文件类型
const fileName = assetInfo.name || "";
const extType = fileName.split(".").pop()?.toLowerCase();
// 图片文件归类到 images 目录
if (/png|jpe?g|gif|svg|webp|ico/i.test(extType || "")) {
return "images/[name]-[hash][extname]";
}
// 字体文件归类到 fonts 目录
if (/woff2?|eot|ttf|otf/i.test(extType || "")) {
return "fonts/[name]-[hash][extname]";
}
// CSS 文件归类到 css 目录
if (extType === "css") {
return "css/[name]-[hash][extname]";
}
// video 和 audio 文件归类到 media 目录
if (/mp4|webm|ogg|mp3|wav|flac|aac/i.test(extType || "")) {
return "media/[name]-[hash][extname]";
}
// 其他资源文件归类到 assets 目录
return "assets/[name]-[hash][extname]";
},
},
},
// chunk 大小警告限制 (kb)
chunkSizeWarningLimit: 1000,
commonjsOptions: {
include: [/wangeditor/, /node_modules/],
},
},
server: {
host: "0.0.0.0", // 允许外部访问
port: 5173, // 明确指定端口
open: true, // 自动打开浏览器
proxy: {
"/api": {
target: env.VITE_API_BASE_URL, // 目标服务器地址
changeOrigin: true,
secure: false, // 如果是http协议,需要设置为false
rewrite: (path) => {
console.log("代理路径:", path); // 添加日志查看代理是否生效
return path.replace(/^\/api/, "");
},
// 添加更详细的配置
configure: (proxy, options) => {
proxy.on("error", (err, req, res) => {
console.log("代理错误:", err);
});
proxy.on("proxyReq", (proxyReq, req, res) => {
console.log(
"代理请求:",
req.method,
req.url,
"->",
options.target + req.url,
);
});
},
},
// 示例:将 /api/s3 的请求代理到另一个服务器
"/api/s3": {
target: "https://www.baidu.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api\/s3/, ""),
},
},
},
};
});