- 创建项目
bash
npx degit dcloudio/uni-preset-vue#vite-ts [项目名称]
2.创建env目录
多环境配置文件命名为.env.别名
添加index.d.ts
TypeScript
interface ImportMetaEnv{
readonly VITE_ENV:string,
readonly UNI_PLATFORM:string,
readonly VITE_APPID:string,
readonly VITE_NAME:string
readonly VITE_VERSION:string
readonly VITE_API_BASE_URL:string
}
interface ImportMeta{
readonly env:ImportMetaEnv;
}
3.修改vite.config.ts
TypeScript
import { defineConfig, loadEnv,type PluginOption } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import {resolve } from 'path'
import { copyToDeployDir } from "./post-build-plugin";
import { modifyVersion } from "./version-plugin";
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd()+"/env", ['VITE_']);
return {
envDir:resolve(__dirname, 'env'),
plugins: [
modifyVersion(mode,env),
uni(),
copyToDeployDir(mode,env)
],
resolve:{
alias:{
'@':resolve(__dirname, 'src')
}
}
}
});
post-build-plugin.ts文件内容为:
TypeScript
import { loadEnv,type PluginOption } from "vite";
import {resolve } from 'path';
import fs from 'fs-extra';
//拷贝到发布目录
export function copyToDeployDir(mode: string,baseEnv :Record<string,string>) : PluginOption {
return{
name: 'copy-to-deploy',
enforce: 'post',
async closeBundle() {
try{
if (!baseEnv.VITE_NAME) {
throw new Error('VITE_NAME environment variable is not defined');
}
const nodeEnv = baseEnv.VITE_USER_NODE_ENV == "development" ? "dev":"build";
// 路径安全处理
const sourceDir = resolve(__dirname, 'dist');
const destDir = resolve(__dirname, 'deploy', baseEnv.VITE_NAME);
await fs.copy(sourceDir, destDir, { overwrite: true });
console.log(`✅ 文件已复制到: ${destDir}`);
if(baseEnv.VITE_PLATFORM =="mp-toutiao"){
await createPackageFile(destDir, nodeEnv, baseEnv);
}
await updateProjectFile(destDir, nodeEnv, baseEnv);
} catch (error) {
console.error('❌ 文件复制失败:', error instanceof Error ? error.message : error);
process.exit(1); // 构建失败时退出
}
}
}
}
//创建package.json文件
async function createPackageFile(destDir:string, nodeEnv:string, env:Record<string,string>){
const filePath = resolve(destDir, nodeEnv, env.VITE_PLATFORM,"package.json")
const content = "{\"industrySDK\": true}";
await fs.writeFile(filePath, content);
console.log(`✅ package.json文件已创建`);
}
//更新项目 appid ,项目名称
async function updateProjectFile(destDir:string, nodeEnv:string,env:Record<string,string>){
const filePath = resolve(destDir, nodeEnv, env.VITE_PLATFORM,"project.config.json")
const content = fs.readFileSync(filePath, 'utf8');
const newContent = content.replace('TT_APPID', env.VITE_APPID).replace('TT_NAME',env.VITE_NAME);
console.log(newContent)
await fs.writeFile(filePath, newContent);
}
4.编译命令执行
bash
pnpm run dev:mp-toutiao-别名
注:package.json中需将编译命令添加
bash
"dev:mp-toutiao-别名": "uni -p mp-toutiao --mode 别名",
5.完整多环境配置工程