项目中vite1.0升级到vite2.0,vite.config.js 配置报错解决方案整理把项目中vite1.0升级到
把项目中vite1.0升级到vite2.0,遇到一些报错,下面是整理的一些解决方法:
1、报错:warning: Duplicate key "server" in object literal
vite.config.js:67:4: warning: Duplicate key "server" in object literal
67 │ server: {
╵ ~~~~~~
vite.config.js:29:4: note: The original "server" is here
29 │ server: {
╵
原因:在vite.config.js里面写了多个server,合在一个里面写就好了
2、报错:Error: Cannot find module 'dotenv'
failed to load config from /Users/duoduo/react-new/tianjin-data-web/vite.config.js
error when starting dev server:
Error: Cannot find module 'dotenv'
Require stack:
解决:安装 npm install dotenv
3、报错:No loader is configured for ".vue"
src/main.ts:19:22: error: No loader is configured for ".vue" files: src/components/v-login-box.vue
19 │ import vLoginBox from "/@/components/v-about.vue"
╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
解决:把vite.config.js中的alias中的"/@/"改为"@",并且全局搜索"/@/",用"@/"替换
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"public": path.resolve(__dirname, "./public"),
},
},
4、接口报错404,原因:代理没有生效,按照下面修改server,要加host和post
server: {
port: process.env.VITE_PORT,
// 是否自动在浏览器打开
open: true,
// 是否开启 https
https: false,
proxy: {
'/api': {
target: 'http://localhost:3333/',
changeOrigin: true,
rewrite: (pathStr) => pathStr.replace('/api', '')
},
},
},
5、build打包到生产环境图片,字体资源路径404
解决办法:先排查build中assetsDir路径,看打包后指向路径是否对的上,如果问题没解决,再检查图片路径是否放在了public,静态资源一定要放在public
build: {
minify: "esbuild",
assetsDir: "",
outDir: `./dist/${process.env.VITE_ENV}`,
},
最后放上总的vite.config.js配置
const fs = require("fs");
import path from "path";
// Dotenv 是一个零依赖的模块,它能将环境变量中的变量从 .env 文件加载到 process.env 中
const dotenv = require("dotenv");
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
const envFiles = [
/** default file */
`.env`,
/** mode file */
`.env.${process.env.NODE_ENV}`,
];
for (const file of envFiles) {
const envConfig = dotenv.parse(fs.readFileSync(file));
for (const k in envConfig) {
process.env[k] = envConfig[k];
}
}
export default defineConfig({
plugins: [vue()],
base: "./",
server: {
port: process.env.VITE_PORT,
// 是否自动在浏览器打开
open: true,
// 是否开启 https
https: false,
proxy: {
'/api': {
target: 'http://localhost:3333/',
changeOrigin: true,
rewrite: (pathStr) => pathStr.replace('/api', '')
},
},
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"public": path.resolve(__dirname, "./public"),
},
},
optimizeDeps: {
include: [
"element-plus",
"element-plus/lib/locale/lang/zh-cn",
"dayjs/locale/zh-cn",
],
},
build: {
// 压缩
minify: "esbuild",
assetsDir: "",
outDir: `./dist/${process.env.VITE_ENV}`,
},
});
转载自:https://juejin.cn/post/6966103581673914382