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 创建小程序,支持多环境导出小程序

相关推荐
阿珊和她的猫1 小时前
CSS3新特性概述
前端·css·css3
前端小端长2 小时前
qiankun 微前端应用入门教程:从搭建到部署
前端
yinuo4 小时前
前端跨页面通讯终极指南⑥:SharedWorker 用法全解析
前端
PineappleCoder9 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪9 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯9 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
源码获取_wx:Fegn08959 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视9 小时前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan9 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
JIngJaneIL10 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot