当前位置: 首页 > news >正文

uniapp+ts 多环境编译

1. 创建项目

npx degit dcloudio/uni-preset-vue#vite-ts [项目名称]

2.创建env目录

多环境配置文件命名为.env.别名

添加index.d.ts


interface ImportMetaEnv{readonly VITE_ENV:string,readonly UNI_PLATFORM:string,readonly VITE_APPID:string,readonly VITE_NAME:stringreadonly VITE_VERSION:stringreadonly VITE_API_BASE_URL:string
}interface ImportMeta{readonly env:ImportMetaEnv;
}

3.修改vite.config.ts

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文件内容为:

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.编译命令执行

pnpm run dev:mp-toutiao-别名

注:package.json中需将编译命令添加

"dev:mp-toutiao-别名": "uni -p mp-toutiao --mode 别名",

5.完整多环境配置工程

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

相关文章:

  • WebSockets 在实时通信中的应用与优化
  • H3C-W2000-G2【透明反代理】
  • 【Linux网络篇】:Socket网络套接字以及简单的UDP网络程序编写
  • 【如何做好一份技术文档?】用Javadoc与PlantUML构建高质量技术文档(API文档自动化部署)
  • 贪心介绍 LeetCode 455.分发饼干 LeetCode 376. 摆动序列 LeetCode 53. 最大子序和
  • 力扣热题100之排序链表
  • leetcode - 前缀和
  • 前端框架token相关bug,前后端本地联调
  • 每日算法刷题Day14 5.24:leetcode不定长滑动窗口求子数组个数越长越合法4道题,用时1h20min
  • 【MySQL】07.表内容的操作
  • leetcode438.找到字符串中所有字母异位词
  • 电脑C盘清理技巧:释放空间,提升性能
  • 微信小程序调试
  • 前端大文件上传性能优化实战:分片上传分析与实战
  • JVM 的垃圾回收机制 GC
  • 【MySQL】06.内置函数
  • tvalid寄存器的理解
  • N2语法 判断,評価
  • Oracle 的SHRINK 操作实现原理
  • SpringAI 大模型应用开发篇-纯 Prompt 开发(舔狗模拟器)、Function Calling(智能客服)、RAG (知识库 ChatPDF)
  • 武山县建设局网站/常州网站推广
  • 淘宝客优惠券网站建设加盟官网/南通百度网站快速优化
  • 哪个网站做视频有钱挣/建网站专业
  • 网站制作./关键词优化策略
  • 网络推广网站/百度400电话
  • 做临时工看哪个网站/整合营销沟通