vue3.0+vite开发过程中遇到的问题汇总
从零开始,根据官网文档独立搭建项目时候遇到的一些问题或方法进行记录、总结
1、node环境要求node v16以上
可以用 nvm 进行node环境管理,nvm安装遇到的问题,个人有做总结,可供参考(https://www.cnblogs.com/mihoutaoguniang/p/16877670.html)
2、找不到模块“vite”。你的意思是要将 "moduleResolution" 选项设置为 "node",还是要将别名添加到 "paths" 选项中

解决方法(tsconfig.json添加如下代码,添加之后重启;重启之后如果仍然有问题,可能是编辑器版本比较旧,升级编辑器版本,我从vscode v1.74.x更新到了v1.85.1解决了):
"compilerOptions": {
"moduleResolution": "node"
}

3、默认端口是 5173,使用端口 3000

4、提示:has no default export

解决方法:插件禁用 Vetur,重启编辑器
4、element不支持vue3,需要使用element-plus
地址:https://element-plus.gitee.io/zh-CN/
5、添加环境变量
--- vite.config.ts同层级创建 .env.development 与 .env.production,配置环境接口地址(VITE_BASE_API)和base地址(VITE_BASE_PATH)

--- /src文件下获取环境变量
import.meta.env.VITE_BASE_API
--- vite.config.ts使用
import { loadEnv } from "vite";
export default ({ mode }: { mode: any }) => {
const env = loadEnv(mode, process.cwd());
return defineConfig({
base: `${env.VITE_BASE_PATH}`,
...
}
})
}
完整代码:
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { loadEnv } from "vite";
export default ({ mode }: { mode: any }) => {
const env = loadEnv(mode, process.cwd());
return defineConfig({
plugins: [
vue(),
vueJsx(),
],
base: `${env.VITE_BASE_PATH}`,
server: {
proxy: {
'/api': {
target: 'xxx',
changeOrigin: true,
cookiePathRewrite: {
'^/api': ''
}
}
},
port: 3000
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
}
6、npm run build 打包之后,通过nginx查看效果,没有展示路由内容,而本地开发环境是正常的
解决方案:
--- vite默认是 createWebHistory 路由模式,改用 createWebHashHistory
--- vite.config.ts 中base 使用 './'
--- src/router/index.ts 中使用 component: () => import('../views/xxx/index')形式,不要直接import,本地没问题,打包不展示 component: import('../views/xxx/index')
import {createRouter, createWebHashHistory} from "vue-router";
// 路由信息
const routes = [
{
path: "/",
name: "Home",
component: () => import('../views/xxx/index'),
},
];
// 导出路由
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router;
7、只能本机访问,同一个局域网访问不了
提示:Network: use `--host` to expose
解决方案:vite.config.ts 添加 host: '0.0.0.0'

有问题欢迎交流!

浙公网安备 33010602011771号