uniapp+ts 多环境编译

  1. 创建项目
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.完整多环境配置工程

playlet: uniapp + typescript + pina 创建小程序,支持多环境导出小程序

相关推荐
前端的日常30 分钟前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师1 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么1 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒1 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_0761 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端
枣把儿1 小时前
开源!公众号排版+一键发布工具懒人版
前端
2501_916007471 小时前
抓包工具功能对比,TraceEagle、Charles、Fiddler、Wireshark、mitmproxy 差别
前端·网络协议·ios·adb·https·fiddler·wireshark
Flynt2 小时前
AI 写的页面一眼假?有人把"假指纹"写成 62 条规则,不用大模型就能跑
前端·ai编程·claude
kyriewen2 小时前
我把 10 道面试题答案真跑了一遍:6 道是错的
前端·javascript·面试
WebInfra2 小时前
Rspack 2.3 发布:联手 SWC 团队带来全新编译器
前端·javascript·github