Created
June 12, 2018 07:11
-
-
Save zcyemi/b21f769a36d31ece7e99a954c11877e6 to your computer and use it in GitHub Desktop.
使用Gulp构建Egret微信小游戏
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"projectfolder": "TestMap", | |
"wxappid": "wx6ac********", | |
"projectname":"testproj", | |
"res":{ | |
"compressFolders": [ | |
"spriteatlas", | |
"UIAtlas" | |
] | |
}, | |
"ossconf":{ | |
"connect":{ | |
"region": "oss-cn-hangzhou", | |
"accessKeyId": "[oss key]", | |
"accessKeySecret":"[oss secret]", | |
"bucket": "[oss buckname]" | |
}, | |
"controls":{ | |
"headers":{ | |
"Cache-Control": "no-cache" | |
} | |
}, | |
"setting":{ | |
"dir":"/", | |
"noClean": false, | |
"force": false, | |
"quiet": true | |
} | |
}, | |
"ossconf_cache":{ | |
"cacheFileName":"Cache/oss/" | |
}, | |
"server_rul": "https://test.com" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const gulp = require('gulp'); | |
const fs = require('fs-extra'); | |
const path = require('path'); | |
const run = require('gulp-run'); | |
const md5File = require('md5-file'); | |
const tinypng = require('gulp-tinypng-nokey'); | |
const filter = require('gulp-filter'); | |
const crypto = require('crypto'); | |
const merge = require('gulp-merge'); | |
const rimraf = require('gulp-rimraf'); | |
const vinyl = require('vinyl'); | |
const ossSync = require('gulp-oss-sync'); | |
const gulpSeq = require('gulp-sequence'); | |
const winreg = require('winreg'); | |
const os= require('os'); | |
const shell = require('shelljs'); | |
const iconv = require('iconv-lite'); | |
const{ exec } = require('child_process'); | |
const through = require('through2'); | |
const Config = JSON.parse(fs.readFileSync('config.json').toString()); | |
const ProjectFolder = Config.projectfolder; | |
const ProjectFolderWX = ProjectFolder + '_wxgame'; | |
const ProjectResFolder = ProjectFolder + '_res_' + GetProjectHash(); | |
gulp.task("run_remote", gulpSeq( | |
"export_clean", | |
"wx_copy", | |
["wx_setid","copy_cisconfig"], | |
"egret_build", | |
"res_clean", | |
[ | |
"res_process_img", | |
"res_process_json" | |
], | |
"wx_resclean", | |
"oss_sync", | |
"run_wx" | |
)); | |
gulp.task("run", gulpSeq( | |
"export_clean", | |
"wx_copy", | |
["wx_setid","copy_cisconfig"], | |
"egret_build", | |
"run_wx" | |
)); | |
gulp.task("egret_run", () => { | |
return gulp.src(Config.projectfolder) | |
.pipe(run('egret run', { | |
cwd: './' + Config.projectfolder, | |
verbosity: 2 | |
})); | |
}); | |
gulp.task("egret_build",async () => { | |
let out = await new Promise((res,rej)=>{ | |
exec("egret build",{encoding: 'gbk',cwd: path.join(process.cwd(),Config.projectfolder)},(err,stdout,stderr)=>{ | |
console.log(iconv.decode(stderr,"gbk")); | |
res(iconv.decode(stdout,"gbk")); | |
}); | |
}) | |
console.log(out); | |
}); | |
gulp.task("wx_copy", () => { | |
let appdatPath = process.env.APPDATA || (process.platform == 'darwin' ? (path.join(process.env.HOME, 'Library/Preferences' )): '/var/local'); | |
if(os.platform() === 'darwin'){ | |
appdatPath = path.join(process.env.HOME,'Library/Application\ Support'); | |
} | |
let egretwxpath = path.join(appdatPath, 'EgretLauncher/download/EgretWeixinSupport'); | |
if (!fs.existsSync(egretwxpath)) { | |
console.error('egret wxtarget not exists: ' + egretwxpath); | |
return; | |
} | |
let subdirs = fs.readdirSync(egretwxpath).filter(d => fs.lstatSync(path.join(egretwxpath, d)).isDirectory() && d.startsWith('egret-weixin-support')); | |
subdirs.sort(); | |
let usedwxVer = subdirs[subdirs.length - 1]; | |
const templatepath = path.join(egretwxpath, usedwxVer, usedwxVer, 'template'); | |
if (!fs.existsSync(templatepath)) { | |
console.error("egert wxtarget template not exist: " + templatepath); | |
return; | |
} | |
console.log('use egret wxtarget: ' + usedwxVer); | |
console.log(templatepath); | |
return gulp.src(templatepath + '/**/*.{png,json,js}') | |
.pipe(gulp.dest(ProjectFolderWX)); | |
}) | |
gulp.task("wx_setid", ["wx_copy"], () => { | |
let projconfig = path.join(ProjectFolderWX, "project.config.json"); | |
let wxconfig = JSON.parse(fs.readFileSync(projconfig).toString()); | |
if (Config.wxappid != undefined) wxconfig.appid = Config.wxappid; | |
if (Config.projectname != undefined) wxconfig.projectname = Config.projectname; | |
fs.writeFileSync(projconfig, JSON.stringify(wxconfig, null, 2)); | |
}); | |
const RES_FILTER = { | |
"Image": ProjectFolder + '/resource/assets/**/*.{png,jpg,jpeg}', | |
"Json": ProjectFolder + '/resource/**/*.json', | |
"Exml": ProjectFolder + '/resource/**/*.exml', | |
}; | |
gulp.task("res_process_img", () => { | |
return gulp.src(RES_FILTER.Image) | |
.pipe(filter((file) => CheckImageCache(file))) | |
.pipe(tinypng()) | |
.pipe(gulp.dest(ProjectResFolder + '/resource/assets/')) | |
.pipe(filter(file => { | |
RestoreImageToCache(file); | |
return true; | |
})); | |
}); | |
gulp.task("res_process_json", () => { | |
return gulp.src(RES_FILTER.Json) | |
.pipe(gulpJsonMin()) | |
.pipe(gulp.dest(ProjectResFolder + '/resource/')); | |
}) | |
gulp.task("export_clean",()=>{ | |
return gulp.src(ProjectFolderWX) | |
.pipe(rimraf()); | |
}); | |
gulp.task("res_clean", () => { | |
return gulp.src(ProjectResFolder + '/resource/') | |
.pipe(rimraf()); | |
}); | |
gulp.task("oss_sync", () => { | |
SetUpCISConfig(true,Config.server_rul+ ProjectResFolder+"/resource/"); | |
let ossconf = Config.ossconf; | |
ossconf.setting.dir = ProjectResFolder; | |
let ossconfCache = Config.ossconf_cache; | |
return gulp.src(ProjectResFolder + '/**/*') | |
.pipe(ossSync(Config.ossconf, ossconfCache)); | |
}); | |
gulp.task("wx_resclean",()=>{ | |
return gulp.src(ProjectFolderWX + '/resource/') | |
.pipe(rimraf()); | |
}) | |
gulp.task("run_wx",()=>{ | |
RunWXdev(ProjectFolderWX); | |
}) | |
gulp.task("copy_cisconfig",()=>{ | |
return gulp.src(ProjectFolder+'/cis/**/*') | |
.pipe(gulp.dest(ProjectFolderWX+'/cis/')); | |
}) | |
function GetProjectHash() { | |
let str = ProjectFolder + process.cwd(); | |
return crypto.createHash('md5').update(str).digest('hex'); | |
} | |
function CheckImageCache(file) { | |
//if(!file.path.endsWith('.png')) return false; | |
let filehash = md5File.sync(file.path); | |
let cachePath = 'Cache/image/'; | |
let filepath = path.join(cachePath, filehash + '.png'); | |
let tarPath = path.join(process.cwd(), ProjectResFolder + '/resource/assets/', file.relative); | |
let compressFolders = Config.res.compressFolders; | |
let filedir = path.dirname(file.relative); | |
if (!compressFolders.includes(filedir)) { | |
//skip compress,copy directory to target | |
//console.log("skip file:" + file.relative); | |
CheckDir(tarPath); | |
fs.copyFile(file.path, tarPath, e => { | |
if (e) { | |
throw e; | |
} | |
}); | |
return false; | |
} | |
if (fs.existsSync(filepath)) { | |
console.log("usecache: " + file.relative); | |
CheckDir(tarPath); | |
fs.copyFile(filepath, tarPath, e => { | |
if (e) { | |
console.log(e.message); | |
throw e; | |
} | |
}); | |
return false; | |
} | |
return true; | |
} | |
function RestoreImageToCache(file) { | |
let destPath = path.join(ProjectResFolder + '/resource/assets/', file.relative); | |
let srcPath = path.join(ProjectFolder + '/resource/assets/', file.relative); | |
md5File(srcPath, (err, filehash) => { | |
let cachePath = path.join('Cache/image/', filehash + '.png'); | |
console.log('SaveCache: ' + cachePath); | |
fs.copyFile(destPath, cachePath, e => { | |
if (e) { | |
throw e; | |
} | |
}); | |
}); | |
} | |
function CheckDir(filepath) { | |
let dir = path.dirname(filepath); | |
if (!fs.existsSync(dir)) { | |
fs.ensureDirSync(dir); | |
} | |
} | |
async function RunWXdev(projpath) { | |
let wxPaths; | |
let packagePath; | |
switch (os.platform()) { | |
case "darwin": | |
wxPaths = "/Applications/wechatwebdevtools.app/Contents/Resources/app.nw/bin/cli"; | |
packagePath = "/Applications/wechatwebdevtools.app/Contents/Resources/app.nw/package.json"; | |
break; | |
case "win32": | |
wxPaths = await new Promise((res,rej)=>{ | |
exec("reg query HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Tencent\\微信web开发者工具",{encoding: 'gbk'},(err,stdout,stderr)=>{ | |
var clipath = iconv.decode(stdout,"gbk"); | |
clipath = clipath.split(' ')[3].trim(); | |
clipath = path.join(path.dirname(clipath),"cli.bat"); | |
res(clipath); | |
}); | |
}) | |
.catch(err=>{throw err}); | |
break; | |
} | |
//console.log(wxPaths); | |
if(wxPaths == null){ | |
console.log("fetch wxdevtool path failed!"); | |
return; | |
} | |
let cmd = "\""+wxPaths+"\" -o "+ path.join(process.cwd(),projpath); | |
exec(cmd,(err,stdout,stderr)=>{ | |
console.log(stdout); | |
console.log(stderr); | |
}); | |
} | |
function SetUpCISConfig(isremote,resPath){ | |
let cisconfpath = path.join(process.cwd(),ProjectFolderWX+"/cis/cisconfig.json"); | |
let cisconf = JSON.parse(fs.readFileSync(cisconfpath).toString()); | |
cisconf.res.use_remote = isremote; | |
cisconf.res.remote_url = resPath; | |
cisconf.res.remote_json_url = resPath+"default.res.json"; | |
fs.writeFileSync(cisconfpath,JSON.stringify(cisconf)); | |
} | |
function gulpJsonMin(){ | |
return through.obj(function(file,enc,cb){ | |
if(file.isNull()){ | |
cb(null,file); | |
return; | |
} | |
if(file.isBuffer()){ | |
let contents = JSON.parse(file.contents); | |
FixNumber(contents,5); | |
file.contents = Buffer.from(JSON.stringify(contents)); | |
cb(null,file); | |
return; | |
} | |
if(file.isStream()){ | |
console.log("stream: skip"); | |
cb(null,file); | |
return; | |
} | |
}); | |
} | |
function FixNumber(obj,size){ | |
for(let m in obj){ | |
let mt = typeof(obj[m]); | |
if(mt === 'number'){ | |
obj[m]=Number(obj[m].toFixed(size)); | |
} | |
else if(mt === 'object'){ | |
FixNumber(obj[m],size); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment