_publish_1566379668010.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // v1.2.0
  2. //是否使用IDE自带的node环境和插件,设置false后,则使用自己环境(使用命令行方式执行)
  3. const useIDENode = process.argv[0].indexOf("LayaAir") > -1 ? true : false;
  4. //获取Node插件和工作路径
  5. let ideModuleDir = useIDENode ? process.argv[1].replace("gulp\\bin\\gulp.js", "").replace("gulp/bin/gulp.js", "") : "";
  6. let workSpaceDir = useIDENode ? process.argv[2].replace("--gulpfile=", "").replace("\\.laya\\publish.js", "").replace("/.laya/publish.js", "") + "/" : "./../";
  7. //引用插件模块
  8. const gulp = require(ideModuleDir + "gulp");
  9. const fs = require("fs");
  10. const path = require("path");
  11. const uglify = require(ideModuleDir + "gulp-uglify");
  12. const jsonminify = require(ideModuleDir + "gulp-jsonminify");
  13. const image = require(ideModuleDir + "gulp-image");
  14. const rev = require(ideModuleDir + "gulp-rev");
  15. const revdel = require(ideModuleDir + "gulp-rev-delete-original");
  16. const revCollector = require(ideModuleDir + 'gulp-rev-collector');
  17. const del = require(ideModuleDir + "del");
  18. const requireDir = require(ideModuleDir + 'require-dir');
  19. global.ideModuleDir = ideModuleDir;
  20. global.workSpaceDir = workSpaceDir;
  21. // 结合compile.js使用
  22. global.publish = true;
  23. const fileList = ["compile.js", "publish_xmgame.js", "publish_oppogame.js"];
  24. requireDir('./', {
  25. filter: function (fullPath) {
  26. // 只用到了compile.js和publish.js
  27. if (fileList.includes(path.basename(fullPath))) {
  28. return true;
  29. } else {
  30. return false;
  31. }
  32. }
  33. });
  34. // 清理临时文件夹,加载配置
  35. let config,
  36. releaseDir,
  37. platform,
  38. isOpendataProj = false;
  39. gulp.task("loadConfig", function () {
  40. platform = "web"
  41. if (!useIDENode && process.argv.length > 5 && process.argv[4] == "--config") {
  42. platform = process.argv[5].replace(".json", "");
  43. }
  44. if (useIDENode && process.argv.length >= 4 && process.argv[3].startsWith("--config") && process.argv[3].endsWith(".json")) {
  45. platform = process.argv[3].match(/(\w+).json/)[1];
  46. }
  47. let _path;
  48. if (!useIDENode) {
  49. _path = platform + ".json";
  50. releaseDir = "../release/" + platform;
  51. }
  52. if (useIDENode) {
  53. _path = path.join(workSpaceDir, ".laya", `${platform}.json`);
  54. releaseDir = path.join(workSpaceDir, "release", platform).replace(/\\/g, "/");
  55. }
  56. global.platform = platform;
  57. let file = fs.readFileSync(_path, "utf-8");
  58. if (file) {
  59. file = file.replace(/\$basePath/g, releaseDir);
  60. config = JSON.parse(file);
  61. global.config = config;
  62. }
  63. // 是否是开放域项目
  64. let projInfoPath = path.join(workSpaceDir, path.basename(workSpaceDir) + ".laya");
  65. let isExist = fs.existsSync(projInfoPath);
  66. if (isExist) {
  67. try {
  68. let projInfo = fs.readFileSync(projInfoPath, "utf8");
  69. projInfo = projInfo && JSON.parse(projInfo);
  70. isOpendataProj = projInfo.layaProType === 12;
  71. } catch (e) {}
  72. }
  73. });
  74. // 重新编译项目
  75. // gulp.task("compile", ["loadConfig"], function () {
  76. // if (config.compile) {
  77. // console.log("compile");
  78. // }
  79. // });
  80. // 清理release文件夹
  81. gulp.task("clearReleaseDir", ["compile"], function (cb) {
  82. if (config.clearReleaseDir) {
  83. let delList = [releaseDir, releaseDir + "_pack", config.packfileTargetValue];
  84. // 小米快游戏,使用即存的项目,删掉Laya工程文件,保留小米环境项目文件
  85. if (platform === "xmgame") {
  86. let xmProjSrc = path.join(releaseDir, config.xmInfo.projName);
  87. // 不要删掉manifest.json/main.js文件
  88. // 这里不是node-glob语法,详见: https://github.com/sindresorhus/del
  89. delList = [`${xmProjSrc}/**`, `!${xmProjSrc}`, `!${xmProjSrc}/node_modules/**`, `!${xmProjSrc}/sign/**`, `!${xmProjSrc}/{babel.config.js,main.js,manifest.json,package.json,package-lock.json}`];
  90. } else if (platform === "oppogame") {
  91. let oppoProjSrc = path.join(releaseDir, config.oppoInfo.projName);
  92. delList = [`${oppoProjSrc}/**`, `!${oppoProjSrc}`, `!${oppoProjSrc}/dist/**`, `!${oppoProjSrc}/{manifest.json}`];
  93. }
  94. del(delList, { force: true }).then(paths => {
  95. cb();
  96. });
  97. } else cb();
  98. });
  99. // copy bin文件到release文件夹
  100. gulp.task("copyFile", ["clearReleaseDir"], function () {
  101. let baseCopyFilter = [`${workSpaceDir}/bin/**/*.*`];
  102. // 只拷贝index.js中引用的类库
  103. if (config.onlyIndexJS) {
  104. baseCopyFilter = baseCopyFilter.concat(`!${workSpaceDir}/bin/libs/*.*`);
  105. }
  106. if (platform === "wxgame" && isOpendataProj) { // 开放域项目微信发布,仅拷贝用到的文件
  107. config.copyFilesFilter = [`${workSpaceDir}/bin/js/bundle.js`, `${workSpaceDir}/bin/index.js`, `${workSpaceDir}/bin/game.js`];
  108. if (config.projectType !== "as") { // 开放域精简类库
  109. config.copyFilesFilter.push(`${workSpaceDir}/bin/libs/laya.opendata.min.js`);
  110. }
  111. } else if (platform === "wxgame") { // 微信项目,不拷贝index.html,不拷贝百度bin目录中的文件
  112. config.copyFilesFilter = baseCopyFilter.concat([`!${workSpaceDir}/bin/index.html`, `!${workSpaceDir}/bin/{project.swan.json,swan-game-adapter.js}`]);
  113. } else if (platform === "bdgame") { // 百度项目,不拷贝index.html,不拷贝微信bin目录中的文件
  114. config.copyFilesFilter = baseCopyFilter.concat([`!${workSpaceDir}/bin/index.html`, `!${workSpaceDir}/bin/{project.config.json,weapp-adapter.js}`]);
  115. } else { // web|QQ项目|小米快游戏,不拷贝微信、百度在bin目录中的文件
  116. config.copyFilesFilter = baseCopyFilter.concat([`!${workSpaceDir}/bin/{game.js,game.json,project.config.json,weapp-adapter.js,project.swan.json,swan-game-adapter.js}`]);
  117. }
  118. // 小米快游戏,需要新建一个快游戏项目,拷贝的只是项目的一部分,将文件先拷贝到文件夹的临时目录中去
  119. let QUICKGAMELIST = ["xmgame", "oppogame"];
  120. if (QUICKGAMELIST.includes(platform)) {
  121. releaseDir = global.tempReleaseDir = path.join(releaseDir, "temprelease");
  122. }
  123. global.releaseDir = releaseDir;
  124. var stream = gulp.src(config.copyFilesFilter, { base: `${workSpaceDir}/bin` });
  125. return stream.pipe(gulp.dest(releaseDir));
  126. });
  127. // copy libs中的js文件到release文件夹
  128. gulp.task("copyLibsJsFile", ["copyFile"], function () {
  129. if (!config.onlyIndexJS) {
  130. return;
  131. }
  132. if (platform === "wxgame" && isOpendataProj) { // 开放域项目微信发布,拷贝文件时已经拷贝类库文件了
  133. return;
  134. }
  135. // 开放域项目,as语言,没有libs目录,mac系统报错
  136. let libs = path.join(workSpaceDir, "bin", "libs");
  137. if (!fs.existsSync(libs)) {
  138. return;
  139. }
  140. // 分析index.js
  141. let indexJSPath = path.join(workSpaceDir, "bin", "index.js");
  142. let indexJsContent = fs.readFileSync(indexJSPath, "utf8");
  143. let libsList = indexJsContent.match(/loadLib\(['"]libs\/[a-zA-z0-9\/\.]+\.(js|wasm)['"]\)/g);
  144. if (!libsList) {
  145. libsList = [];
  146. }
  147. let
  148. item,
  149. libsName = "",
  150. libsStr = "";
  151. for (let i = 0, len = libsList.length; i < len; i++) {
  152. item = libsList[i];
  153. libsName = item.match(/loadLib\(['"]libs\/([a-zA-z0-9\/\.]+\.(js|wasm))['"]\)/);
  154. libsStr += libsStr ? `,${libsName[1]}` : libsName[1];
  155. }
  156. let copyLibsList = [`${workSpaceDir}/bin/libs/{${libsStr}}`];
  157. if (!libsStr.includes(",")) {
  158. copyLibsList = [`${workSpaceDir}/bin/libs/${libsStr}`];
  159. }
  160. // 微信、百度,需要拷贝对应平台的类库
  161. if (platform === "wxgame") {
  162. copyLibsList.push(`${workSpaceDir}/bin/libs/laya.wxmini.js`);
  163. } else if (platform === "bdgame") {
  164. copyLibsList.push(`${workSpaceDir}/bin/libs/laya.bdmini.js`);
  165. }
  166. var stream = gulp.src(copyLibsList, { base: `${workSpaceDir}/bin` });
  167. return stream.pipe(gulp.dest(releaseDir));
  168. });
  169. // 根据不同的项目类型拷贝平台文件
  170. gulp.task("copyPlatformFile", ["copyLibsJsFile"], function () {
  171. let fileLibsPath;
  172. if (useIDENode) {
  173. fileLibsPath = path.join(ideModuleDir, "../", "out", "layarepublic", "LayaAirProjectPack", "lib", "data");
  174. } else if (process.argv.length >= 8 && process.argv[6] === "--libspath") {
  175. fileLibsPath = process.argv[7];
  176. console.log("平台文件包是否存在: " + fs.existsSync(fileLibsPath));
  177. } else {
  178. console.log("没有接收到可用文件包位置,不拷贝对应平台文件");
  179. return;
  180. }
  181. // 开放域项目,微信发布
  182. if (platform === "wxgame" && isOpendataProj) {
  183. let platformDir = path.join(fileLibsPath, "wxfiles", "weapp-adapter.js");
  184. let stream = gulp.src(platformDir);
  185. return stream.pipe(gulp.dest(releaseDir));
  186. }
  187. // 微信项目,非开放域项目
  188. if (platform === "wxgame") {
  189. // 如果新建项目时已经点击了"微信/百度小游戏bin目录快速调试",不再拷贝
  190. let isHadWXFiles =
  191. fs.existsSync(path.join(workSpaceDir, "bin", "game.js")) &&
  192. fs.existsSync(path.join(workSpaceDir, "bin", "game.json")) &&
  193. fs.existsSync(path.join(workSpaceDir, "bin", "project.config.json")) &&
  194. fs.existsSync(path.join(workSpaceDir, "bin", "weapp-adapter.js"));
  195. if (isHadWXFiles) {
  196. return;
  197. }
  198. let platformDir = path.join(fileLibsPath, "wxfiles");
  199. let stream = gulp.src(platformDir + "/*.*");
  200. return stream.pipe(gulp.dest(releaseDir));
  201. }
  202. // qq玩一玩项目,区分语言
  203. if (platform === "qqwanyiwan") {
  204. let projectLangDir = config.projectType;
  205. let platformDir = path.join(fileLibsPath, "qqfiles", projectLangDir);
  206. let stream = gulp.src(platformDir + "/**/*.*");
  207. return stream.pipe(gulp.dest(releaseDir));
  208. }
  209. // 百度项目
  210. if (platform === "bdgame") {
  211. // 如果新建项目时已经点击了"微信/百度小游戏bin目录快速调试",不再拷贝
  212. let isHadBdFiles =
  213. fs.existsSync(path.join(workSpaceDir, "bin", "game.js")) &&
  214. fs.existsSync(path.join(workSpaceDir, "bin", "game.json")) &&
  215. fs.existsSync(path.join(workSpaceDir, "bin", "project.swan.json")) &&
  216. fs.existsSync(path.join(workSpaceDir, "bin", "swan-game-adapter.js"));
  217. if (isHadBdFiles) {
  218. return;
  219. }
  220. let platformDir = path.join(fileLibsPath, "bdfiles");
  221. let stream = gulp.src(platformDir + "/*.*");
  222. return stream.pipe(gulp.dest(releaseDir));
  223. }
  224. });
  225. // 拷贝文件后,针对特定平台修改文件内容
  226. gulp.task("modifyFile", ["copyPlatformFile"], function () {
  227. // QQ玩一玩
  228. if (platform === "qqwanyiwan") {
  229. // 修改bundle.js
  230. let bundleFilePath = path.join(releaseDir, "js", "bundle.js");
  231. if (fs.existsSync(bundleFilePath)) {
  232. let fileContent = fs.readFileSync(bundleFilePath, "utf8");
  233. var appendCode = 'if(window["BK"]&&window["BK"]["Sprite"]){BK.Script.loadlib("GameRes://layaforqq/laya.bkadpter.js");}';
  234. if (fileContent.includes("/**LayaGameStart**/") && !fileContent.includes(appendCode)) {
  235. fileContent = fileContent.split("/**LayaGameStart**/").join(`/**LayaGameStart**/\n${appendCode}`);
  236. fs.writeFileSync(bundleFilePath, fileContent, "utf8");
  237. }
  238. }
  239. // 修改index.js
  240. let indexFilePath = path.join(releaseDir, "index.js");
  241. if (fs.existsSync(indexFilePath)) {
  242. let fileContent = fs.readFileSync(indexFilePath, "utf8");
  243. fileContent = fileContent.replace(/loadLib\("/g, "BK.Script.loadlib(\"GameRes://");
  244. // 非as语言,要添加类库
  245. if ("as" !== config.projectType) {
  246. if (fileContent.includes("//-----libs-end-------")) {
  247. fileContent = fileContent.split("//-----libs-end-------").join(`//-----libs-end-------\nBK.Script.loadlib("GameRes://layaforqq/laya.bkadpter.js");`);
  248. }
  249. }
  250. fs.writeFileSync(indexFilePath, fileContent, "utf8");
  251. }
  252. // 修改main.js
  253. let mainFilePath = path.join(releaseDir, "main.js");
  254. if (fs.existsSync(mainFilePath)) {
  255. let fileContent = fs.readFileSync(mainFilePath, "utf8");
  256. fileContent = `BK.Script.loadlib("GameRes://layaforqq/qqPlayCore.js");
  257. BK.Script.loadlib("GameRes://layaforqq/bkadptpre.js");
  258. BK.Script.loadlib("GameRes://layaforqq/domparserinone.js");
  259. BK.Script.loadlib("GameRes://index.js");`;
  260. fs.writeFileSync(mainFilePath, fileContent, "utf8");
  261. }
  262. return;
  263. }
  264. // 百度项目,修改index.js
  265. if (platform === "bdgame") {
  266. let filePath = path.join(releaseDir, "index.js");
  267. if (!fs.existsSync(filePath)) {
  268. return;
  269. }
  270. let fileContent = fs.readFileSync(filePath, "utf8");
  271. fileContent = fileContent.replace(/loadLib\(/g, "require(");
  272. fs.writeFileSync(filePath, fileContent, "utf8");
  273. return;
  274. }
  275. });
  276. // 压缩json
  277. gulp.task("compressJson", ["modifyFile"], function () {
  278. if (config.compressJson) {
  279. return gulp.src(config.compressJsonFilter, { base: releaseDir })
  280. .pipe(jsonminify())
  281. .pipe(gulp.dest(releaseDir));
  282. }
  283. });
  284. // 压缩js
  285. gulp.task("compressJs", ["compressJson"], function () {
  286. if (config.compressJs) {
  287. return gulp.src(config.compressJsFilter, { base: releaseDir })
  288. .pipe(uglify())
  289. .on('error', function (err) {
  290. console.warn(err.toString());
  291. })
  292. .pipe(gulp.dest(releaseDir));
  293. }
  294. });
  295. // 压缩png,jpg
  296. gulp.task("compressImage", ["compressJs"], function () {
  297. if (config.compressImage) {
  298. return gulp.src(config.compressImageFilter, { base: releaseDir })
  299. .pipe(image({
  300. pngquant: true, //PNG优化工具
  301. optipng: false, //PNG优化工具
  302. zopflipng: true, //PNG优化工具
  303. jpegRecompress: false, //jpg优化工具
  304. mozjpeg: true, //jpg优化工具
  305. guetzli: false, //jpg优化工具
  306. gifsicle: false, //gif优化工具
  307. svgo: false, //SVG优化工具
  308. concurrent: 10, //并发线程数
  309. quiet: true //是否是静默方式
  310. // optipng: ['-i 1', '-strip all', '-fix', '-o7', '-force'],
  311. // pngquant: ['--speed=1', '--force', 256],
  312. // zopflipng: ['-y', '--lossy_8bit', '--lossy_transparent'],
  313. // jpegRecompress: ['--strip', '--quality', 'medium', '--min', 40, '--max', 80],
  314. // mozjpeg: ['-optimize', '-progressive'],
  315. // guetzli: ['--quality', 85]
  316. }))
  317. .pipe(gulp.dest(releaseDir));
  318. }
  319. });
  320. // 开放域的情况下,合并game.js和index.js,并删除game.js
  321. gulp.task("openData", ["compressImage"], function (cb) {
  322. if (config.openDataZone) {
  323. let indexPath = releaseDir + "/index.js";
  324. let indexjs = readFile(indexPath);
  325. let gamejs = readFile(releaseDir + "/game.js");
  326. if (gamejs && indexjs) {
  327. gamejs = gamejs.replace('require("index.js")', indexjs);
  328. fs.writeFileSync(indexPath, gamejs, 'utf-8');
  329. }
  330. if (isOpendataProj) {
  331. // 开放域项目,将game.js删掉,发布最小包
  332. del(`${releaseDir}/game.js`, { force: true }).then(paths => {
  333. cb();
  334. });
  335. } else {
  336. cb();
  337. }
  338. } else {
  339. cb();
  340. }
  341. });
  342. function readFile(path) {
  343. if (fs.existsSync(path)) {
  344. return fs.readFileSync(path, "utf-8");
  345. }
  346. return null;
  347. }
  348. // 生成版本管理信息
  349. gulp.task("version1", ["openData"], function () {
  350. if (config.version) {
  351. return gulp.src(config.versionFilter, { base: releaseDir })
  352. .pipe(rev())
  353. .pipe(gulp.dest(releaseDir))
  354. .pipe(revdel())
  355. .pipe(rev.manifest("version.json"))
  356. .pipe(gulp.dest(releaseDir));
  357. }
  358. });
  359. // 替换index.js里面的变化的文件名
  360. gulp.task("version2", ["version1"], function () {
  361. if (config.version) {
  362. //替换index.html和index.js里面的文件名称
  363. let htmlPath = releaseDir + "/index.html";
  364. let versionPath = releaseDir + "/version.json";
  365. let gameJSPath = releaseDir + "/game.js";
  366. let mainJSPath = releaseDir + "/main.js";
  367. let indexJSPath;
  368. let versionCon = fs.readFileSync(versionPath, "utf8");
  369. versionCon = JSON.parse(versionCon);
  370. indexJSPath = releaseDir + "/" + versionCon["index.js"];
  371. // 替换config.packfileFullValue中的路径
  372. let packfileStr = JSON.stringify(config.packfileFullValue).replace(/\\\\/g, "/");
  373. let tempPackfile = `${workSpaceDir}/.laya/configTemp.json`;
  374. fs.writeFileSync(tempPackfile, packfileStr, "utf8");
  375. let srcList = [versionPath, indexJSPath, tempPackfile];
  376. if (fs.existsSync(htmlPath)) {
  377. srcList.push(htmlPath);
  378. }
  379. if (fs.existsSync(gameJSPath)) {
  380. srcList.push(gameJSPath);
  381. }
  382. if (fs.existsSync(mainJSPath)) {
  383. srcList.push(mainJSPath);
  384. }
  385. return gulp.src(srcList)
  386. .pipe(revCollector())
  387. .pipe(gulp.dest(releaseDir));
  388. }
  389. });
  390. // 筛选4M包
  391. gulp.task("packfile", ["version2"], function() {
  392. if (config.version) {
  393. // 从release目录取得带有版本号的目录
  394. let tempPackfile = `${workSpaceDir}/.laya/configTemp.json`;
  395. let releasePackfile = `${releaseDir}/configTemp.json`;
  396. let packfileStr = fs.readFileSync(releasePackfile, "utf8");
  397. config.packfileFullValue = JSON.parse(packfileStr);
  398. // 删掉临时目录
  399. fs.unlinkSync(tempPackfile);
  400. fs.unlinkSync(releasePackfile);
  401. }
  402. if (config.packfile) { // 提取本地包(文件列表形式)
  403. return gulp.src(config.packfileFullValue, { base: releaseDir })
  404. .pipe(gulp.dest(config.packfileTargetValue || releaseDir + "_pack"));
  405. }
  406. });
  407. // 起始任务
  408. gulp.task("publish", ["buildXiaomiProj", "buildOPPOProj"], function () {
  409. console.log("All tasks completed!");
  410. });