主要利用shelljs库将shell脚本的命令转化为js语法,从而达到在windows上写shell脚本的目的。
一、写如下示例代码所需环境配置
1.1 nodejs 环境变量1.2 gradle 环境变量
1.3 git 环境变量
二、示例源代码如下:
var shell = require('shelljs');
var fs = require('fs');
// 命令行参数 第一个参数是表示更不更新引擎工程代,第二个参数表示是否重新安装引擎工程依赖
// node .\windowsAndroidBuildRelase.js -u -g //-u表示更新引擎工程代码,-g重新安装依赖包
var commandLineArgs = process.argv.slice(2);
// 返回上级目录
shell.cd('..')
// 返回上级目录
shell.cd('..')
//获取当前的绝对路径
var platformsPath = shell.pwd()
//向控制台输出路径
shell.echo("platformsPath::"+platformsPath)
//在当前文件路径下执行android打包操作
shell.exec('cordova build android -r')
//打包成功后移除android/assets/www/static/engine路径下的engine文件夹
shell.rm('-rf', 'android/assets/www/static/engine')
//将路径切换至xxxx目录工程下面
shell.cd('xxxx')
var enginePath = shell.pwd()
shell.echo("enginePath::"+enginePath)
//判断引擎工程是否下载了node_modules依赖,true为下载了
var nodeModulesExists = fs.existsSync(enginePath+"\\node_modules")
if((commandLineArgs[1]&&commandLineArgs[1]==='-g')||!nodeModulesExists){
shell.rm('-rf',enginePath+"\\node_modules")
shell.exec('npm install')
}
var distExists = fs.existsSync(enginePath+"\\dist")
//如果第一个命令行参数存在,并且等于-u,说明需要重新编译引擎工程
if((commandLineArgs[0]&&commandLineArgs[0]==='-u')||!distExists){
shell.exec('git remote -v')
shell.exec('git pull')
shell.rm('-rf',enginePath+"\\dist")
shell.exec('npm run build')
}
//拷贝文件
shell.cp('-Rf',enginePath+'\\dist\\*', platformsPath+'\\android\\assets\\www\\static\\engine')
shell.exec(`node ${platformsPath}\\resource\\shell\\windowsReplaceEngineUrl.js`)
//回到platformsPath路径下
shell.cd('..')
//切入到android目录之中
shell.cd('android')
//执行gradle打包命令
shell.exec('gradle --scan assembleRelease')