vite
大约 3 分钟react
环境变量
编译时环境变量
在项目根目录下创建文件 .env.development 作为开发环境下的配置文件,类似的文件 .env.production 表示生产环境,测试环境是 .env.stag。下面以为开发环境文件 .env.development 为例:
# 设置为开发模式
NODE_ENV = development
# 自定义参数,API地址,必须以 VITE_ 开头。不需要引号,VITE自动认为是字符串
# 可通过 import.meta.env.VITE_BASE_API 调用本参数
VITE_BASE_API = /api
在封装的 request.ts 中使用环境变量的案例
import { message } from 'antd'
import axios, { AxiosError } from 'axios'
import { showLoading, hideLoading } from './loadingSVG'
const instance = axios.create({
baseURL: import.meta.env.VITE_BASE_API,
timeout: 5000, // 请求超时,单位毫秒
timeoutErrorMessage: '请求超时,请稍后再试!',
withCredentials: true // 允许跨域
})
通过命令 yarn dev 运行项目时,自动运用开发环境下的 API 前缀,通过 yarn build 编译项目时自动运用生产环境下的 API 前缀,所以要保证所有环境变量文件中的变量名称统一
别名src
在 vite 配置文件 vite.config.ts 中如下设置,将源码根目录下的 src 目录别名为 @
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
root: './', // 项目入口文件在本配置文件同级目录下,即文件 index.html
//base: '/api', // 浏览器地址栏中主机+端口号后面的项目名称
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
server: {
//host: 'localhost',
//port: 7101,
proxy: {
'/api': {
target: 'https://www.xdfznh.club/wxpadbe',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
}
})
之后在业务组件中引用其他组件时:import Test from '@/views/Test'(注意前提是在目录 Test 下的组件文件名称为:index.tsx,开发环境默认搜索目录下名称为 index 的文件)
如 vscode 报错:Cannot find module '@/views/Test' or its corresponding type declarations 说明 vscode 没有识别到该配置,在文件 tsconfig.json 中配置如下
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
//"files": [],
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}
如果 vscode 仍然报同样的错误则在兄弟文件 tsconfig.app.json 和 tsconfig.node.json 中也添加该别名,注意 paths 必须和 baseUrl 一起使用,所以要添加的具体代码如下
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
代理服务器
下面的 vite 配置文件 vite.config.ts 中要求 api 开头的代理为云端的后台服务
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
root: './', // 项目入口文件在本配置文件同级目录下,即文件 index.html
//base: '/api', // 浏览器地址栏中主机+端口号后面的项目名称
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
server: {
//host: 'localhost',
//port: 7101,
proxy: {
'/api': {
target: 'https://染厂云服务域名/wxpadbe',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
}
})
要求 axios 设置 baseURL,下面是 src/utils/request.ts 文件的代码
import axios from 'axios'
const instance = axios.create({
baseURL: '/api',
timeout: 5000, // 请求超时,单位毫秒
timeoutErrorMessage: '请求超时,请稍后再试!',
withCredentials: true // 允许跨域
})
export default {
get(url: string, params?: unknown) {
return instance.get(url, { params })
},
post(url: string, params: unknown) {
return instance.post(url, params)
}
}
业务组件请求
import request from '../utils/request'
function Welcome() {
request
.get('/test/getJavaDate')
.then(res => {
console.log(res.data)
})
.catch(err => console.log(err))
return <span>Welcome</span>
}
export default Welcome
