环境搭建
一、vite 初始化
npm create vite@latest
二、安装vscode扩展
Vue Language Features (Volar)
TypeScript Vue Plugin (Volar)
安装完成后将 Vetur 插件禁用
三、创建配置文件
根目录新建
.env.production 生产环境配置文件
.env.development 开发环境配置文件
.env.example 配置说明文件,不写真实配置
.env 备选配置文件,当配置项在所有文件中找不到时,会到.env文件中查找
四、安装sass
npm i -D sass
五、配置 vite.config
- 安装插件
npm install dotenv --save
npm i --save-dev @types/node # vue项目中使用nodejs模块
- 配置环境变量 .env.development
# 项目标题
VITE_APP_TITLE = 项目名称
# 请求基准路径
VITE_BASE_URL = /api
# 服务器域名
VITE_DOMAIN_HOST = http://xxx.xxx.com
- 添加自定义的环境变量名称,实现TS智能提示
src / vite-env.d.ts
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
interface ImportMetaEnv {
readonly VITE_APP_TITLE: string
readonly VITE_BASE_URL: string
readonly VITE_DOMAIN_HOST: string
// 更多环境变量...
}
- 修改配置文件
vite.config.ts
import { readFileSync } from 'fs'
import path from 'path'
import { defineConfig, CommonServerOptions } from 'vite'
import vue from '@vitejs/plugin-vue'
import dotenv from 'dotenv'
// 获取项目绝对路径
const resolve = (dir: string) => path.resolve(__dirname,'.', dir)
// https://vitejs.dev/config/
// export default defineConfig({
// plugins: [vue()]
// })
export default defineConfig(config => {
const { mode } = config
// 当前环境变量文件
const curEnv = `.env.${mode}`
// 服务配置
let server: CommonServerOptions = {}
// 读取配置文件
const {
VITE_HOST,
VITE_PORT,
VITE_BASE_URL,
VITE_DOMAIN_HOST
} = dotenv.parse(readFileSync(curEnv))
// 根据当前环境加载不同的服务配置
switch (curEnv) {
case 'development':
server = {
host: VITE_HOST,
port: parseInt(VITE_PORT),
proxy: {
[VITE_BASE_URL]: {
target: VITE_DOMAIN_HOST,
changeOrigin: true,
// rewrite: (path) => path.replace(/^\/api/, '')
},
}
}
break
default:
server = {
host: VITE_HOST,
port: parseInt(VITE_PORT),
}
}
// 返回配置项
return {
plugins: [vue()],
server,
resolve: {
alias: {
'@': resolve('/src')
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/assets/scss/global.scss";'
}
}
}
}
})