官網(wǎng):https://uniapp.dcloud.net.cn/collocation/package.html#%E7%94%A8%E6%B3%95
小程序開發(fā)完成之后需要一套代碼多個小程序使用,每次都需要在manifest.json文件中手動修改,大大增加了開發(fā)的復(fù)雜度。
官網(wǎng):https://uniapp.dcloud.net.cn/collocation/package.html#%E7%94%A8%E6%B3%95
小程序開發(fā)完成之后需要一套代碼多個小程序使用,每次都需要在manifest.json文件中手動修改,大大增加了開發(fā)的復(fù)雜度,動態(tài)獲取appid,便于維護小程序數(shù)據(jù)。
一、修改 package.json 擴展配置
"uni-app": {
"scripts": {
"fbl": {
"title": "賦百齡",
"env": {
"UNI_PLATFORM": "mp-weixin",
"ENV_TYPE": "fbl"
},
"define": {
"MP-WEIXIN": true
}
},
"wlsc": {
"title": "無量商城",
"env": {
"UNI_PLATFORM": "mp-weixin",
"ENV_TYPE": "wlsc"
},
"define": {
"MP-WEIXIN": true
}
}
}
},
補充:
{
/**
* package.json其它原有配置
* 拷貝代碼后請去掉注釋!
*/
"uni-app": {// 擴展配置
"scripts": {
"custom-platform": { //自定義編譯平臺配置,可通過cli方式調(diào)用
"title":"自定義擴展名稱", // 在HBuilderX中會顯示在 運行/發(fā)行 菜單中
"browser":"", //運行到的目標(biāo)瀏覽器,僅當(dāng)UNI_PLATFORM為h5時有效
"env": {//環(huán)境變量
"UNI_PLATFORM": "", //基準(zhǔn)平臺
"MY_TEST": "", // ... 其他自定義環(huán)境變量
},
"define": { //自定義條件編譯
"CUSTOM-CONST": true //自定義條件編譯常量,建議為大寫
}
}
}
}
}
Tips: ●
UNI_PLATFORM僅支持填寫uni-app默認(rèn)支持的基準(zhǔn)平臺,目前僅限如下枚舉值:h5、mp-weixin、mp-alipay、mp-baidu、mp-toutiao、mp-qq
● browser
僅在UNI_PLATFORM為h5時有效,目前僅限如下枚舉值:chrome、firefox、ie、edge、safari、hbuilderx
● package.json文件中不允許出現(xiàn)注釋,否則擴展配置無效 ● vue-cli 需更新到最新版,HBuilderX需升級到
2.1.6+ 版本
二、根目錄創(chuàng)建config/env.ts 文件
type EnvConfigType = {
appid: string
appName: string
appLogoUrl: string
}
// 翻倍了
const fbl: EnvConfigType = {
appid: 'wx123cbb5e',
appName: '翻倍了',
}
// 為了生存
const wlsc: EnvConfigType = {
appid: 'wxd4573',
appName: '為了生存',
}
// 注意:這里的屬性名要和上面package.json中定義的擴展節(jié)點編譯名稱相同
const ENV_CONFIG = {
fbl,
wlsc,
}
module.exports = ENV_CONFIG
三、 vite.config.ts 配置文件,修改appid
import { defineConfig } from 'vite'
import VueTypeImports from 'vite-plugin-vue-type-imports'
import uni from '@dcloudio/vite-plugin-uni'
// 導(dǎo)入fs模塊
const fs = require('fs')
// 導(dǎo)入環(huán)境變量配置文件
const ENV_CONFIG = require('./config/env.ts')
const manifestPath = `${__dirname}/src/manifest.json` // 注意一下自己配置的 manifestPath 是否正確
let Manifest = fs.readFileSync(manifestPath, {
encoding: 'utf-8',
})
function replaceManifest(path: string, value: string) {
const arr = path.split('.')
const len = arr.length
const lastItem = arr[len - 1]
let i = 0
const ManifestArr = Manifest.split(/\n/)
for (let index = 0; index < ManifestArr.length; index++) {
const item = ManifestArr[index]
if (new RegExp(`"${arr[i]}"`).test(item)) ++i
if (i === len) {
const hasComma = /,/.test(item)
ManifestArr[index] = item.replace(
new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
`"${lastItem}": ${value}${hasComma ? ',' : ''}`,
)
break
}
}
Manifest = ManifestArr.join('\n')
}
// 獲取執(zhí)行命令
const ENV_TYPE = JSON.parse(process.env.UNI_CUSTOM_DEFINE)['ENV_TYPE'] // 打印出來是否正確
// 讀取環(huán)境變量內(nèi)容
const appid = ENV_CONFIG[ENV_TYPE].appid
if (appid) {
replaceManifest('mp-weixin.appid', `"${appid}"`)
}
fs.writeFileSync(manifestPath, Manifest, { flag: 'w' })
// https://vitejs.dev/config/
export default defineConfig({
build: {
// 開發(fā)階段啟用源碼映射:https://uniapp.dcloud.net.cn/tutorial/migration-to-vue3.html#需主動開啟-sourcemap
sourcemap: process.env.NODE_ENV === 'development',
},
plugins: [uni(), VueTypeImports()],
})
四、運行及發(fā)布項目
1、啟動命令
vue-cli開發(fā)者可通過如下命令,啟動釘釘小程序平臺的編譯
運行項目
npm run dev:custom fbl
npm run dev:custom wlsc
發(fā)布項目
npm run build:custom fbl
npm run build:custom wlsc
HBuilderX會根據(jù)package.json的擴展配置,在運行、發(fā)行菜單下,生成自定義菜單(釘釘小程序),開發(fā)者點擊對應(yīng)菜單編譯運行即可,如下圖:
2、修改啟動命令
添加指令
"dev:mp-fbl": "uni -p fbl",
"dev:mp-wlsc": "uni -p wlsc",
"build:mp-fbl": "uni -p fbl",
"build:mp-wlsc": "uni -p wlsc",
啟動打包命令:
# 啟動
npm run dev:mp-fbl
npm run dev:mp-wlsc
# 打包
npm run build:mp-fbl
npm run build:mp-wlsc
五、獲取自定義環(huán)境配置的信息
可以在 vite.config.ts 文件中,添加 define 共享選項 。
1、vite 的 define 共享選項
2、配置共享選項
我們可以將處理好的當(dāng)前微信小程序環(huán)境配置信息,放到共享選項中的常量中,修改vite.config.ts文件。
import { defineConfig } from 'vite'
import VueTypeImports from 'vite-plugin-vue-type-imports'
import uni from '@dcloudio/vite-plugin-uni'
// 導(dǎo)入fs模塊
const fs = require('fs')
// 導(dǎo)入環(huán)境變量配置文件
const ENV_CONFIG = require('./config/env.ts')
const manifestPath = `${__dirname}/src/manifest.json`
let Manifest = fs.readFileSync(manifestPath, {
encoding: 'utf-8',
})
function replaceManifest(path: string, value: string) {
const arr = path.split('.')
const len = arr.length
const lastItem = arr[len - 1]
let i = 0
const ManifestArr = Manifest.split(/\n/)
for (let index = 0; index < ManifestArr.length; index++) {
const item = ManifestArr[index]
if (new RegExp(`"${arr[i]}"`).test(item)) ++i
if (i === len) {
const hasComma = /,/.test(item)
ManifestArr[index] = item.replace(
new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
`"${lastItem}": ${value}${hasComma ? ',' : ''}`,
)
break
}
}
Manifest = ManifestArr.join('\n')
}
// 獲取執(zhí)行命令
const ENV_TYPE = JSON.parse(process.env.UNI_CUSTOM_DEFINE)['ENV_TYPE']
// 讀取環(huán)境變量內(nèi)容
const appid = ENV_CONFIG[ENV_TYPE].appid
if (appid) {
replaceManifest('mp-weixin.appid', `"${appid}"`)
}
fs.writeFileSync(manifestPath, Manifest, { flag: 'w' })
console.log(ENV_CONFIG[ENV_TYPE])
// https://vitejs.dev/config/
export default defineConfig({
build: {
// 開發(fā)階段啟用源碼映射:https://uniapp.dcloud.net.cn/tutorial/migration-to-vue3.html#需主動開啟-sourcemap
sourcemap: process.env.NODE_ENV === 'development',
},
plugins: [uni(), VueTypeImports()],
// 定義全局常量替換方式。其中每項在開發(fā)環(huán)境下會被定義在全局,而在構(gòu)建時被靜態(tài)替換。
define: {
_PROCESS_ENV_APP_INFO: ENV_CONFIG[ENV_TYPE],
},
})
3、頁面獲取自定義環(huán)境配置信息
打開App.vue文件,在 onShow 里面去執(zhí)行倉儲的賦值。文章來源:http://www.zghlxwxcb.cn/news/detail-834131.html
1)倉儲創(chuàng)建
import { defineStore } from 'pinia'
export const useAppInfoStore = defineStore('appInfo', () => {
const appInfo = ref<{ appid: string, appName: string, appLogoUrl: string }>(uni.getStorageSync('_appInfo'))
// 獲取緩存小程序自定義環(huán)境配置信息
const setAppInfo = (appData: { appid: string; appName: string; appLogoUrl: string }) => {
appInfo.value = appData
uni.setStorage({
key: '_appInfo',
data: appData,
})
}
return { setAppInfo, appInfo }
})
2)在App.vue文件中執(zhí)行賦值操作
<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { useThemesStore, useAppInfoStore } from '@/stores'
const themesStore = useThemesStore()
const appInfoStore = useAppInfoStore()
onLaunch(() => {
console.log('App Launch')
})
onShow(() => {
console.log('App Show', getCurrentPages())
themesStore.actionThemeCfg() // 執(zhí)行倉儲賦值
appInfoStore.setAppInfo(_PROCESS_ENV_APP_INFO) // 設(shè)置app信息
})
onHide(() => {
console.log('App Hide')
})
// #ifndef MP-WEIXIN
// 隱藏原生的底部tabbar
uni.hideTabBar()
// #endif
</script>
<style lang="scss">
</style>
取值:文章來源地址http://www.zghlxwxcb.cn/news/detail-834131.html
import { useAppInfoStore } from '@/stores'
const { appInfo } = useAppInfoStore()
<image
v-if="appInfo.appLogoUrl"
class="app-logo"
mode="heightFix"
:src="appInfo.appLogoUrl"
/>
<text v-else>{{ appInfo.appName }}</text>
到了這里,關(guān)于動態(tài)獲取 微信小程序appid / 自定義啟動命令的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!