vite 读取命令行变量作为接口请求地址
当前版本 “vite”: “^4.1.4”
1. 命令行 实际打包时,改这里的环境变量即可
当然, 感觉最佳实践是在CI/CD中设置环境变量
npm run build --API_PROXY=/url/
2.package.json
"scripts": {
"predev": "node ./scripts/getApiUrl.js",
"dev": "vite",
"prebuild": "node ./scripts/getApiUrl.js",
"build": "vite build",
},
3.scripts
// scripts/getApiUrl.js
var fs = require('fs');
var path = require('path');
// 写入
var fsWrite = function (content) {
// 写入到默认值配置文件中
var pwd = process.cwd();
var apiConfigPath = path.resolve(pwd, "src/api/hostIp.js");
fs.writeFileSync(apiConfigPath, content);
}
var apiProxy = process.env.npm_config_api_proxy;
if (apiProxy) {
var content = `export const hostIp = "${apiProxy}";
export default "${apiProxy}";`;
fsWrite(content)
} else {
// 获取到当前的pre命令
var eventName = process.env.npm_lifecycle_event
var command = eventName == 'prebuild' ? 'build' : 'dev'
// 打包必须填写 API_PROXY
if (command == 'build') {
throw new Error('❌❌❌:\033[41;30m 请在命令行后添加请求地址,例如: \033[40;31m npm run build --API_PROXY=/url/ \033[0m')
} else {
var content = `const ip = import.meta.env.VITE_IP;
export const hostIp = ip;
export default hostIp;`
fsWrite(content)
}
}
4.生成的hostIp文件
npm run dev
// src/api/hostIp.js
// 开发环境
const ip = import.meta.env.VITE_IP; // 从环境变量中获取
export const hostIp = ip;
export default hostIp;
npm run build --API_PROXY=/url/
// src/api/hostIp.js
// 生产(打包)环境
export const hostIp = "/url/";
export default hostIp;
5.请求接口的js文件
// src/api/modules/examine.js
import axios from 'axios'
import { hostIp } from './../hostIp'
axios.post(`${hostIp}getList`, {pageSize:10,pageNum:1})
6.环境变量文件配置
//.env.development
VITE_IP = '/qsh/'
7.完整的项目目录
├─scripts
│ getApiUrl.js
│
└─src
├─api
│ │ .DS_Store
│ │ hostIp.js
│ │
│ └─modules
│ examine.js
│ ...........
│ .env.development
│ .env.production
│ package.json