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

相关推荐
王林不想说话6 分钟前
React + Ant Design 后台项目:63 个业务组件的分层实践
react.js·typescript·ant design
xywww16820 分钟前
真实后台页实测:Opus 5 看图写前端的可用边界在哪
linux·服务器·前端·数据库·人工智能·gpt
小小尚@39 分钟前
AE脚本-AE Actions v1.1.8 操作动作记录器
开发语言·前端·javascript·jupyter·postman
大家的林语冰1 小时前
👍 超越 ESLint,Oxc 优先采用 TypeScript 7,Rust 和 Go 梦幻联动!
前端·javascript·typescript
樊小肆2 小时前
# 你还在等DeepSeek官方 agent Harness‌? 来试试 DeepSeeker-Code吧
前端·人工智能·后端
樊小肆2 小时前
2568 万 token 才花 2 块 2:聊聊 DeepSeeker-Code 怎么吃满上下文缓存
前端·人工智能·后端
JarvanMo3 小时前
Flutter 3.47: material/cupertino终于解耦了
前端
郭邯3 小时前
一次「字符洁癖」引发的思考:我用 AI 写了个全角半角转换工具
前端
想要成为糕糕手3 小时前
🚀 在浏览器里跑 DeepSeek-R1?WebGPU 端侧推理实战(五)—— 中断、重置、缓存与流式生成
前端·react.js·llm
GuWenyue3 小时前
后端接口又双叒没写好?3 步搭建前端 Mock,从此告别"傻等后端"
前端·mocha