根目录添加autoBuild.js
const chalk = require('chalk')
const shell = require('shelljs')
const FS = require('fs')
const paths = require('path')
const errorLog = (error) => console.log(chalk.red(`---------------> ${error}`))
const defaultLog = (log) => console.log(chalk.blue(`---------------> ${log}`))
const successLog = (log) => console.log(chalk.green(`---------------> ${log}`))
// 读取文件,并且替换文件中指定的字符串
const replaceFile = function (filePath, sourceRegx, targetStr) {
return new Promise((resolve) => {
FS.readFile(filePath, function (err, data) {
if (err) {
errorLog(err)
return err
}
let str = data.toString()
str = str.replace(sourceRegx, targetStr)
FS.writeFile(filePath, str, function (err) {
if (err) return err
successLog('替换成功')
resolve()
})
})
})
}
const replaceAppid = async (isReturn = false) => {
defaultLog('开始替换appid')
// 遍历statics文件夹,找到main_*.js
return new Promise((resolve, reject) => {
FS.readdir('./src/utils', (err, files) => {
if (err) {
errorLog(err)
reject(err)
return err
}
if (files.length != 0) {
files.forEach((item) => {
const path = `./src/utils/${item}`
// 判断文件的状态,用于区分文件名/文件夹
FS.stat(path, async (err, status) => {
if (err) {
errorLog(err)
reject(err)
return err
}
const isFile = status.isFile() // 是文件
if (isFile) {
if (item.match(/^config.*$/)) {
defaultLog('替换config.js')
//-------命令自己替换------
if (isReturn) {
await replaceFile(
path,
/const buildFlag = 'ABuild'/g,
"const buildFlag = 'BBuild'"
)
} else {
await replaceFile(
path,
/const buildFlag = 'BBuild'/g,
"const buildFlag = 'ABuild'"
)
}
resolve(true)
}
}
})
})
}
})
})
}
const replaceManifestJsonAppid = async (isReturn = false) => {
defaultLog('开始替换appid')
// 遍历statics文件夹,manifest.json
return new Promise((resolve, reject) => {
FS.readdir('./src', (err, files) => {
if (err) {
errorLog(err)
reject(err)
return err
}
if (files.length != 0) {
files.forEach((item) => {
const path = `./src/${item}`
// 判断文件的状态,用于区分文件名/文件夹
FS.stat(path, async (err, status) => {
if (err) {
errorLog(err)
reject(err)
return err
}
const isFile = status.isFile() // 是文件
if (isFile) {
if (item.match(/^manifest.*$/)) {
defaultLog('替换manifest.json')
//------id自己替换------
if (isReturn) {
await replaceFile(
path,
/Aappid/g,
'Bappid'
)
} else {
await replaceFile(
path,
/Bappid/g,
'Aappid'
)
}
resolve(true)
}
}
})
})
}
})
})
}
// 打包 npm run build
const compileDist = async () => {
defaultLog('开始编译')
// 进入本地文件夹
shell.cd(paths.resolve(process.cwd(), './'))
// ------直接打包,不同自己替换------
shell.exec('npm run build:mp-weixin')
successLog('编译完成')
}
async function runTask() {
await replaceAppid(false)
await replaceManifestJsonAppid(false)
await compileDist()
await replaceAppid(true)
await replaceManifestJsonAppid(true)
}
runTask()
// package.json配置命令,运行这个js
"a:build": "node autoBuild.js",