publish.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // v1.6.1
  2. //是否使用IDE自带的node环境和插件,设置false后,则使用自己环境(使用命令行方式执行)
  3. const useIDENode = process.argv[0].indexOf("LayaAir") > -1 ? true : false;
  4. const useCMDNode = process.argv[1].indexOf("layaair2-cmd") > -1 ? true : false;
  5. function useOtherNode(){
  6. return useIDENode||useCMDNode;
  7. }
  8. //获取Node插件和工作路径
  9. let ideModuleDir = useOtherNode() ? process.argv[1].replace("gulp\\bin\\gulp.js", "").replace("gulp/bin/gulp.js", "") : "";
  10. let workSpaceDir = useOtherNode() ? process.argv[2].replace("--gulpfile=", "").replace("\\.laya\\publish.js", "").replace("/.laya/publish.js", "") + "/" : "./../";
  11. //引用插件模块
  12. const gulp = require(ideModuleDir + "gulp");
  13. const fs = require("fs");
  14. const path = require("path");
  15. const uglify = require(ideModuleDir + 'gulp-uglify-es').default;
  16. const jsonminify = require(ideModuleDir + "gulp-jsonminify");
  17. const image = require(ideModuleDir + "gulp-image");
  18. const rev = require(ideModuleDir + "gulp-rev");
  19. const revdel = require(ideModuleDir + "gulp-rev-delete-original");
  20. const revCollector = require(ideModuleDir + 'gulp-rev-collector');
  21. const del = require(ideModuleDir + "del");
  22. const requireDir = require(ideModuleDir + 'require-dir');
  23. const babel = require(ideModuleDir + 'gulp-babel');
  24. global.ideModuleDir = ideModuleDir;
  25. global.workSpaceDir = workSpaceDir;
  26. // 结合compile.js使用
  27. global.publish = true;
  28. const fileList = ["compile.js", "publish_xmgame.js", "publish_oppogame.js", "publish_vivogame.js", "publish_wxgame.js", "publish_bdgame.js", "publish_qqgame.js"];
  29. requireDir('./', {
  30. filter: function (fullPath) {
  31. // 只用到了compile.js和publish.js
  32. if (fileList.includes(path.basename(fullPath))) {
  33. return true;
  34. } else {
  35. return false;
  36. }
  37. }
  38. });
  39. const QUICKGAMELIST = ["xmgame", "oppogame", "vivogame"];
  40. // 清理临时文件夹,加载配置
  41. let config,
  42. releaseDir,
  43. binPath,
  44. platform = "web",
  45. isOpendataProj = false,
  46. platformCopyTask = [],// 平台脚本拷贝任务
  47. platformTask = []; // 平台需要执行的任务
  48. //任务对照列表
  49. const copyTasks = {
  50. "biligame": "copyPlatformFile_Bili",
  51. "Alipaygame": "copyPlatformFile_Alipay",
  52. "vivogame": "copyPlatformFile_VIVO",
  53. "oppogame": "preCreate_OPPO",
  54. "xmgame": "copyPlatformFile_XM",
  55. "bdgame": "copyPlatformFile_BD",
  56. "qqgame": "copyPlatformFile_QQ",
  57. "wxgame": "copyPlatformFile_WX",
  58. "web": "copyLibsJsFile"
  59. }
  60. const tasks = {
  61. "biligame": "buildBiliProj",
  62. "Alipaygame": "buildAlipayProj",
  63. "vivogame": "buildVivoProj",
  64. "oppogame": "buildOPPOProj",
  65. "xmgame": "buildXiaomiProj",
  66. "bdgame": "buildBDProj",
  67. "qqgame": "buildQQProj",
  68. "wxgame": "buildWXProj",
  69. "web": "packfile"
  70. }
  71. if (!useOtherNode() && process.argv.length > 5 && process.argv[4] == "--config") {
  72. platform = process.argv[5].replace(".json", "");
  73. }
  74. if (useOtherNode() && process.argv.length >= 4 && process.argv[3].startsWith("--config") && process.argv[3].endsWith(".json")) {
  75. platform = process.argv[3].match(/(\w+).json/)[1];
  76. platformCopyTask.push(copyTasks[platform]);
  77. platformTask.push(tasks[platform]);
  78. }
  79. gulp.task("loadConfig", function () {
  80. let _path;
  81. if (!useOtherNode()) {
  82. _path = platform + ".json";
  83. releaseDir = "../release/" + platform;
  84. binPath = "../bin/";
  85. }
  86. if (useOtherNode()) {
  87. _path = path.join(workSpaceDir, ".laya", `${platform}.json`);
  88. releaseDir = path.join(workSpaceDir, "release", platform).replace(/\\/g, "/");
  89. binPath = path.join(workSpaceDir, "bin").replace(/\\/g, "/");
  90. }
  91. global.platform = platform;
  92. let file = fs.readFileSync(_path, "utf-8");
  93. if (file) {
  94. if (QUICKGAMELIST.includes(platform)) {
  95. file = file.replace(/\$basePath/g, releaseDir + "/temprelease");
  96. } else {
  97. file = file.replace(/\$basePath/g, releaseDir);
  98. }
  99. config = JSON.parse(file);
  100. global.config = config;
  101. }
  102. // 是否是开放域项目
  103. let projInfoPath = path.join(workSpaceDir, path.basename(workSpaceDir) + ".laya");
  104. let isExist = fs.existsSync(projInfoPath);
  105. if (isExist) {
  106. try {
  107. let projInfo = fs.readFileSync(projInfoPath, "utf8");
  108. projInfo = projInfo && JSON.parse(projInfo);
  109. isOpendataProj = projInfo.layaProType === 12;
  110. } catch (e) {}
  111. }
  112. });
  113. // 清理release文件夹
  114. gulp.task("clearReleaseDir", ["compile"], function (cb) {
  115. if (config.clearReleaseDir) {
  116. let delList = [`${releaseDir}/**`, releaseDir + "_pack", config.packfileTargetValue];
  117. // 小米快游戏,使用即存的项目,删掉Laya工程文件,保留小米环境项目文件
  118. if (platform === "xmgame") {
  119. let xmProjSrc = path.join(releaseDir, config.xmInfo.projName);
  120. // 不要删掉manifest.json/main.js文件
  121. // 这里不是node-glob语法,详见: https://github.com/sindresorhus/del
  122. delList = [`${xmProjSrc}/**`, `!${xmProjSrc}`, `!${xmProjSrc}/node_modules/**`, `!${xmProjSrc}/sign/**`, `!${xmProjSrc}/{babel.config.js,main.js,manifest.json,package.json,package-lock.json}`];
  123. } else if (platform === "oppogame") {
  124. let oppoProjSrc = path.join(releaseDir, config.oppoInfo.projName);
  125. delList = [`${oppoProjSrc}/**`, `!${oppoProjSrc}`, `!${oppoProjSrc}/dist/**`, `!${oppoProjSrc}/{manifest.json}`];
  126. } else if (platform === "vivogame") {
  127. let vvProj = path.join(releaseDir, config.vivoInfo.projName);
  128. let vvProjSrc = path.join(vvProj, "src");
  129. // 不要删掉manifest.json/main.js文件
  130. // 这里不是node-glob语法,详见: https://github.com/sindresorhus/del
  131. delList = [`${vvProjSrc}/**`, `!${vvProjSrc}`, `!${vvProjSrc}/sign/**`, `!${vvProjSrc}/{game.js,manifest.json}`];
  132. delList = delList.concat(`${vvProj}/engine/**`, `${vvProj}/config/**`);
  133. }
  134. // 保留平台配置文件
  135. if (config.keepPlatformFile) {
  136. if (platform === "wxgame" || platform === "qqgame") {
  137. delList = delList.concat(`!${releaseDir}`, `!${releaseDir}/{game.js,game.json,project.config.json,weapp-adapter.js}`);
  138. } else if (platform === "bdgame") {
  139. delList = delList.concat(`!${releaseDir}`, `!${releaseDir}/{game.js,game.json,project.swan.json,swan-game-adapter.js}`);
  140. } else if (platform === "Alipaygame") {
  141. delList = delList.concat(`!${releaseDir}`, `!${releaseDir}/{game.js,game.json,my-adapter.js}`);
  142. }
  143. }
  144. del(delList, { force: true }).then(paths => {
  145. cb();
  146. });
  147. } else cb();
  148. });
  149. // copy bin文件到release文件夹
  150. gulp.task("copyFile", ["clearReleaseDir"], function () {
  151. let baseCopyFilter = [`${workSpaceDir}/bin/**/*.*`, `!${workSpaceDir}/bin/indexmodule.html`, `!${workSpaceDir}/bin/import/*.*`];
  152. // 只拷贝index.js中引用的类库
  153. if (config.onlyIndexJS) {
  154. baseCopyFilter = baseCopyFilter.concat(`!${workSpaceDir}/bin/libs/*.*`);
  155. }
  156. if (platform === "wxgame" && isOpendataProj) { // 开放域项目微信发布,仅拷贝用到的文件
  157. config.copyFilesFilter = [`${workSpaceDir}/bin/js/bundle.js`, `${workSpaceDir}/bin/index.js`, `${workSpaceDir}/bin/game.js`];
  158. if (config.projectType !== "as") { // 开放域精简类库
  159. config.copyFilesFilter.push(`${workSpaceDir}/bin/libs/laya.opendata.js`);
  160. }
  161. } else if (platform === "wxgame") { // 微信项目,不拷贝index.html,不拷贝百度bin目录中的文件
  162. config.copyFilesFilter = baseCopyFilter.concat([`!${workSpaceDir}/bin/index.html`, `!${workSpaceDir}/bin/{project.swan.json,swan-game-adapter.js}`]);
  163. } else if (platform === "bdgame") { // 百度项目,不拷贝index.html,不拷贝微信bin目录中的文件
  164. config.copyFilesFilter = baseCopyFilter.concat([`!${workSpaceDir}/bin/index.html`, `!${workSpaceDir}/bin/{project.config.json,weapp-adapter.js}`]);
  165. } else { // web|QQ项目|bili|快游戏,不拷贝微信、百度在bin目录中的文件
  166. config.copyFilesFilter = baseCopyFilter.concat([`!${workSpaceDir}/bin/{game.js,game.json,project.config.json,weapp-adapter.js,project.swan.json,swan-game-adapter.js}`]);
  167. }
  168. // bili/alipay/qq,不拷贝index.html
  169. if (["biligame", "Alipaygame", "qqgame"].includes(platform)) {
  170. config.copyFilesFilter = config.copyFilesFilter.concat([`!${workSpaceDir}/bin/index.html`]);
  171. }
  172. // 快游戏,需要新建一个快游戏项目,拷贝的只是项目的一部分,将文件先拷贝到文件夹的临时目录中去
  173. if (QUICKGAMELIST.includes(platform)) {
  174. config.copyFilesFilter = config.copyFilesFilter.concat([`!${workSpaceDir}/bin/index.html`]);
  175. releaseDir = global.tempReleaseDir = path.join(releaseDir, "temprelease");
  176. }
  177. if (config.exclude) { // 排除文件
  178. config.excludeFilter.forEach(function(item, index, list) {
  179. releaseDir = releaseDir.replace(/\\/g, "/");
  180. config.excludeFilter[index] = item.replace(releaseDir, binPath);
  181. });
  182. config.copyFilesFilter = config.copyFilesFilter.concat(config.excludeFilter);
  183. }
  184. global.releaseDir = releaseDir;
  185. var stream = gulp.src(config.copyFilesFilter, { base: `${workSpaceDir}/bin` });
  186. return stream.pipe(gulp.dest(releaseDir));
  187. });
  188. // copy libs中的js文件到release文件夹
  189. gulp.task("copyLibsJsFile", ["copyFile"], function () {
  190. if (!config.onlyIndexJS) {
  191. return;
  192. }
  193. if (platform === "wxgame" && isOpendataProj) { // 开放域项目微信发布,拷贝文件时已经拷贝类库文件了
  194. return;
  195. }
  196. // 开放域项目,as语言,没有libs目录,mac系统报错
  197. let libs = path.join(workSpaceDir, "bin", "libs");
  198. if (!fs.existsSync(libs)) {
  199. return;
  200. }
  201. // 分析index.js
  202. let indexJSPath = path.join(workSpaceDir, "bin", "index.js");
  203. let indexJsContent = fs.readFileSync(indexJSPath, "utf8");
  204. let libsList = indexJsContent.match(/loadLib\(['"]libs\/[\w-./]+\.(js|wasm)['"]\)/g);
  205. if (!libsList) {
  206. libsList = [];
  207. }
  208. let
  209. item,
  210. libsName = "",
  211. libsStr = "";
  212. for (let i = 0, len = libsList.length; i < len; i++) {
  213. item = libsList[i];
  214. libsName = item.match(/loadLib\(['"]libs\/([\w-./]+\.(js|wasm))['"]\)/);
  215. libsStr += libsStr ? `,${libsName[1]}` : libsName[1];
  216. }
  217. // 发布web项目,如果使用了physics3D,默认拷贝runtime
  218. if (platform === "web" && libsStr.includes("laya.physics3D")) {
  219. libsStr += ',laya.physics3D.runtime.js';
  220. }
  221. let copyLibsList = [`${workSpaceDir}/bin/libs/{${libsStr}}`];
  222. if (!libsStr.includes(",")) {
  223. copyLibsList = [`${workSpaceDir}/bin/libs/${libsStr}`];
  224. }
  225. var stream = gulp.src(copyLibsList, { base: `${workSpaceDir}/bin` });
  226. return stream.pipe(gulp.dest(releaseDir));
  227. });
  228. // es6toes5
  229. gulp.task("es6toes5", platformCopyTask, function() {
  230. if (config.es6toes5) {
  231. return gulp.src(`${releaseDir}/**/*.js`, { base: releaseDir })
  232. .pipe(babel({
  233. presets: ['@babel/env'],
  234. compact: true
  235. }))
  236. .pipe(gulp.dest(releaseDir));
  237. }
  238. })
  239. // 压缩json
  240. gulp.task("compressJson", ["es6toes5"], function () {
  241. if (config.compressJson) {
  242. return gulp.src(config.compressJsonFilter, { base: releaseDir })
  243. .pipe(jsonminify())
  244. .pipe(gulp.dest(releaseDir));
  245. }
  246. });
  247. // 压缩js
  248. gulp.task("compressJs", ["compressJson"], function () {
  249. if (config.compressJs) {
  250. return gulp.src(config.compressJsFilter, { base: releaseDir })
  251. .pipe(uglify({
  252. mangle: {
  253. keep_fnames:true
  254. }
  255. }))
  256. .on('error', function (err) {
  257. console.warn(err.toString());
  258. })
  259. .pipe(gulp.dest(releaseDir));
  260. }
  261. });
  262. // 压缩png,jpg
  263. gulp.task("compressImage", ["compressJs"], function () {
  264. if (config.compressImage) {
  265. return gulp.src(config.compressImageFilter, { base: releaseDir })
  266. .pipe(image({
  267. pngquant: true, //PNG优化工具
  268. optipng: false, //PNG优化工具
  269. zopflipng: true, //PNG优化工具
  270. jpegRecompress: false, //jpg优化工具
  271. mozjpeg: true, //jpg优化工具
  272. guetzli: false, //jpg优化工具
  273. gifsicle: false, //gif优化工具
  274. svgo: false, //SVG优化工具
  275. concurrent: 10, //并发线程数
  276. quiet: true //是否是静默方式
  277. // optipng: ['-i 1', '-strip all', '-fix', '-o7', '-force'],
  278. // pngquant: ['--speed=1', '--force', 256],
  279. // zopflipng: ['-y', '--lossy_8bit', '--lossy_transparent'],
  280. // jpegRecompress: ['--strip', '--quality', 'medium', '--min', 40, '--max', 80],
  281. // mozjpeg: ['-optimize', '-progressive'],
  282. // guetzli: ['--quality', 85]
  283. }))
  284. .pipe(gulp.dest(releaseDir));
  285. }
  286. });
  287. // 生成版本管理信息
  288. gulp.task("version1", ["compressImage"], function () {
  289. if (config.version) {
  290. return gulp.src(config.versionFilter, { base: releaseDir })
  291. .pipe(rev())
  292. .pipe(gulp.dest(releaseDir))
  293. .pipe(revdel())
  294. .pipe(rev.manifest("version.json"))
  295. .pipe(gulp.dest(releaseDir));
  296. }
  297. });
  298. // 替换index.js里面的变化的文件名
  299. gulp.task("version2", ["version1"], function () {
  300. if (config.version) {
  301. //替换index.html和index.js里面的文件名称
  302. let htmlPath = releaseDir + "/index.html";
  303. let versionPath = releaseDir + "/version.json";
  304. let gameJSPath = releaseDir + "/game.js";
  305. let mainJSPath = releaseDir + "/main.js";
  306. let indexJSPath;
  307. let versionCon = fs.readFileSync(versionPath, "utf8");
  308. versionCon = JSON.parse(versionCon);
  309. let indexJsStr = (versionCon && versionCon["index.js"]) ? versionCon["index.js"] : "index.js";
  310. indexJSPath = releaseDir + "/" + indexJsStr;
  311. // 替换config.packfileFullValue中的路径
  312. let packfileStr = JSON.stringify(config.packfileFullValue).replace(/\\\\/g, "/");
  313. let tempPackfile = `${workSpaceDir}/.laya/configTemp.json`;
  314. fs.writeFileSync(tempPackfile, packfileStr, "utf8");
  315. let srcList = [versionPath, indexJSPath, tempPackfile];
  316. if (fs.existsSync(htmlPath)) {
  317. srcList.push(htmlPath);
  318. }
  319. if (fs.existsSync(gameJSPath)) {
  320. srcList.push(gameJSPath);
  321. }
  322. if (fs.existsSync(mainJSPath)) {
  323. srcList.push(mainJSPath);
  324. }
  325. return gulp.src(srcList)
  326. .pipe(revCollector())
  327. .pipe(gulp.dest(releaseDir));
  328. }
  329. });
  330. // 筛选4M包
  331. gulp.task("packfile", ["version2"], function() {
  332. if (config.version) {
  333. // 从release目录取得带有版本号的目录
  334. let tempPackfile = `${workSpaceDir}/.laya/configTemp.json`;
  335. let releasePackfile = `${releaseDir}/configTemp.json`;
  336. let packfileStr = fs.readFileSync(releasePackfile, "utf8");
  337. config.packfileFullValue = JSON.parse(packfileStr);
  338. // 删掉临时目录
  339. fs.unlinkSync(tempPackfile);
  340. fs.unlinkSync(releasePackfile);
  341. }
  342. if (config.packfile) { // 提取本地包(文件列表形式)
  343. return gulp.src(config.packfileFullValue, { base: releaseDir })
  344. .pipe(gulp.dest(config.packfileTargetValue || releaseDir + "_pack"));
  345. }
  346. });
  347. // 起始任务
  348. gulp.task("publish", platformTask , function () {
  349. console.log("All tasks completed!");
  350. });