小程序自动上传脚本
小程序自动上传脚本
平时多人开发小程序经常会遇到一个问题:A开发完成后,上传了体验版,然后B也进行开发,开发完成后上传体验版,还需要去后台设置体验版为B的代码,这样就很麻烦了。所以我们可以使用微信小程序提供的
miniprogram-ci
包来实现自动上传。由于我经常使用uni-app
来开发小程序,所以我把脚本放在了uni-app
的/upload
目录下,配合打包命令即可实现打包后自动上传代码。
代码实现
const { execSync } = require('child_process');
const ci = require('miniprogram-ci');
const packageJson = require('../package.json');
const fs = require('fs');
const path = require('path');
/**
* 获取当前 Git用户名
* @returns {string} 返回 Git 用户名
*/
function getGitInfo() {
try {
const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
const user = execSync('git config user.name').toString().trim();
return { branch, user };
} catch (error) {
console.error('获取 Git 信息失败:', error);
return null;
}
}
/**
* 修改版本号
*/
function changeVersion() {
const packageJsonPath = path.join(__dirname, '../package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
const version = packageJson.version;
const versionParts = version.split('.').map(Number);
const env = process.env.NODE_ENV || 'test';
if (env === 'master') {
versionParts[2] += 1;
if (versionParts[2] > 9) {
versionParts[2] = 0;
versionParts[1] += 1;
}
if (versionParts[1] > 9) {
versionParts[1] = 0;
versionParts[0] += 1;
}
}
packageJson.version = versionParts.join('.');
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 4), 'utf8');
console.log('最新版本号为:', packageJson.version);
return version;
}
/**
* 初始化项目信息
* @returns {ci.Project} 返回 ci.Project 对象
*/
function initProjectInfo() {
return new ci.Project({
appid: packageJson.appid,
type: 'miniProgram',
projectPath: './dist/build/mp-weixin',
privateKeyPath: './upload/private.xxxxxxxxxx.key',
});
}
async function upload() {
try {
const project = initProjectInfo();
const { user, branch } = getGitInfo();
const version = changeVersion();
console.log('⏳开始上传');
const uploadResult = await ci.upload({
project,
version,
desc: `${user}在${branch}分支上传了体验版本: ${version}`,
robot: 10,
setting: {
es6: true,
},
onProgressUpdate: console.log,
});
console.log('✅上传成功');
process.exit(0);
} catch (e) {
console.error('❌上传失败:', e);
}
}
upload();
package.json
中添加以下命令:
{
"name": "uni-preset-vue",
"version": "0.0.3",
"appid": "xxxxxxxxxx",
"scripts": {
"buildTest:mp-weixin": "uni build -p mp-weixin --mode test && node upload/index.js",
"buildPre:mp-weixin": "uni build -p mp-weixin --mode pre && node upload/index.js",
"buildMaster:mp-weixin": "uni build -p mp-weixin --mode master && node upload/index.js"
},
}
运行
npm run buildTest:mp-weixin