publish_bytedancegame.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // v1.1.3
  2. const ideModuleDir = global.ideModuleDir;
  3. const workSpaceDir = global.workSpaceDir;
  4. //引用插件模块
  5. const gulp = require(ideModuleDir + "gulp");
  6. const fs = require("fs");
  7. const path = require("path");
  8. const del = require(ideModuleDir + "del");
  9. const revCollector = require(ideModuleDir + 'gulp-rev-collector');
  10. const { getEngineVersion, getFileMd5, canUsePluginEngine } = require("./pub_utils");
  11. const provider = "tt13aa65178c90228a";
  12. const minPluginVersion = "2.7.0";
  13. let fullRemoteEngineList = ["laya.core.js", "laya.filter.js", "laya.ani.js", "laya.tiledmap.js", "laya.d3.js", "laya.html.js", "laya.particle.js", "laya.ui.js", "laya.webgl.js", "laya.filter.js", "laya.d3Plugin.js"];
  14. let copyLibsTask = ["copyPlatformLibsJsFile"];
  15. let versiontask = ["version2"];
  16. let
  17. config,
  18. releaseDir;
  19. let versionCon; // 版本管理version.json
  20. let commandSuffix,
  21. layarepublicPath;
  22. gulp.task("preCreate_ByteDance", copyLibsTask, function() {
  23. releaseDir = global.releaseDir;
  24. config = global.config;
  25. commandSuffix = global.commandSuffix;
  26. layarepublicPath = global.layarepublicPath;
  27. if (config.useMinJsLibs) {
  28. fullRemoteEngineList = fullRemoteEngineList.map((item, index) => {
  29. return item.replace(".js", ".min.js");
  30. })
  31. }
  32. });
  33. gulp.task("copyPlatformFile_ByteDance", ["preCreate_ByteDance"], function() {
  34. let adapterPath = path.join(layarepublicPath, "LayaAirProjectPack", "lib", "data", "bytefiles");
  35. let hasPublishPlatform =
  36. fs.existsSync(path.join(releaseDir, "game.js")) &&
  37. fs.existsSync(path.join(releaseDir, "game.json")) &&
  38. fs.existsSync(path.join(releaseDir, "project.config.json"));
  39. let copyLibsList;
  40. if (hasPublishPlatform) {
  41. copyLibsList = [`${adapterPath}/microgame-adapter.js`];
  42. } else {
  43. copyLibsList = [`${adapterPath}/*.*`];
  44. }
  45. var stream = gulp.src(copyLibsList);
  46. return stream.pipe(gulp.dest(releaseDir));
  47. });
  48. gulp.task("modifyFile_ByteDance", versiontask, function() {
  49. // 修改game.json文件
  50. let gameJsonPath = path.join(releaseDir, "game.json");
  51. let content = fs.readFileSync(gameJsonPath, "utf8");
  52. let conJson = JSON.parse(content);
  53. conJson.deviceOrientation = config.bytedanceInfo.orientation;
  54. if (config.bytedanceInfo.subpack) { // 分包
  55. conJson.subPackages = config.bytedanceSubpack;
  56. // 检测分包目录是否有入口文件
  57. console.log('检查分包文件...');
  58. if (conJson.subPackages) {
  59. for(let i = 0; i < conJson.subPackages.length; i ++) {
  60. let conf = conJson.subPackages[i];
  61. if (conf.root) {
  62. let rootPath = path.join(releaseDir, conf.root);
  63. if (!fs.existsSync(rootPath)) {
  64. throw new Error(`分包文件/目录 ${rootPath} 不存在!`);
  65. }
  66. let jsIndex = rootPath.lastIndexOf('.js');
  67. let jsPath = rootPath;
  68. if (jsIndex < 0 || jsIndex != rootPath.length - 3) {
  69. jsPath = path.join(rootPath, 'game.js');
  70. }
  71. if (!fs.existsSync(jsPath)) {
  72. throw new Error(`分包文件/目录 ${jsPath} 不存在!`);
  73. }
  74. }
  75. }
  76. }
  77. } else {
  78. delete conJson.subPackages;
  79. }
  80. content = JSON.stringify(conJson, null, 4);
  81. fs.writeFileSync(gameJsonPath, content, "utf8");
  82. if (config.version || config.enableVersion) {
  83. let versionPath = releaseDir + "/version.json";
  84. versionCon = fs.readFileSync(versionPath, "utf8");
  85. versionCon = JSON.parse(versionCon);
  86. }
  87. // 修改index.js
  88. let indexJsStr = (versionCon && versionCon["index.js"]) ? versionCon["index.js"] : "index.js";
  89. let indexFilePath = path.join(releaseDir, indexJsStr);
  90. if (!fs.existsSync(indexFilePath)) {
  91. return;
  92. }
  93. let indexFileContent = fs.readFileSync(indexFilePath, "utf8");
  94. indexFileContent = indexFileContent.replace(/loadLib(\(['"])/gm, "require$1./");
  95. fs.writeFileSync(indexFilePath, indexFileContent, "utf8");
  96. })
  97. gulp.task("modifyMinJs_ByteDance", ["modifyFile_ByteDance"], function() {
  98. // 如果保留了平台文件,如果同时取消使用min类库,就会出现文件引用不正确的问题
  99. if (config.keepPlatformFile) {
  100. let fileJsPath = path.join(releaseDir, "game.js");
  101. let content = fs.readFileSync(fileJsPath, "utf-8");
  102. content = content.replace(/min\/laya(-[\w\d]+)?\.ttmini\.min\.js/gm, "laya.ttmini.js");
  103. fs.writeFileSync(fileJsPath, content, 'utf-8');
  104. }
  105. if (!config.useMinJsLibs) {
  106. return;
  107. }
  108. let fileJsPath = path.join(releaseDir, "game.js");
  109. let content = fs.readFileSync(fileJsPath, "utf-8");
  110. content = content.replace(/(min\/)?laya(-[\w\d]+)?\.ttmini(\.min)?\.js/gm, "min/laya.ttmini.min.js");
  111. fs.writeFileSync(fileJsPath, content, 'utf-8');
  112. });
  113. gulp.task("version_ByteDance", ["modifyMinJs_ByteDance"], function() {
  114. // 如果保留了平台文件,如果同时开启版本管理,就会出现文件引用不正确的问题
  115. if (config.keepPlatformFile) {
  116. let fileJsPath = path.join(releaseDir, "game.js");
  117. let content = fs.readFileSync(fileJsPath, "utf-8");
  118. content = content.replace(/laya(-[\w\d]+)?\.ttmini/gm, "laya.ttmini");
  119. content = content.replace(/index(-[\w\d]+)?\.js/gm, "index.js");
  120. fs.writeFileSync(fileJsPath, content, 'utf-8');
  121. }
  122. if (config.version) {
  123. let versionPath = releaseDir + "/version.json";
  124. let gameJSPath = releaseDir + "/game.js";
  125. let srcList = [versionPath, gameJSPath];
  126. return gulp.src(srcList)
  127. .pipe(revCollector())
  128. .pipe(gulp.dest(releaseDir));
  129. }
  130. });
  131. gulp.task("pluginEngin_ByteDance", ["version_ByteDance"], function(cb) {
  132. if (!config.uesEnginePlugin) { // 没有使用引擎插件,还是像以前一样发布
  133. let gameJsonPath = path.join(releaseDir, "game.json");
  134. let gameJsonContent = fs.readFileSync(gameJsonPath, "utf8");
  135. let conJson = JSON.parse(gameJsonContent);
  136. if (conJson.plugins) {
  137. delete conJson.plugins;
  138. gameJsonContent = JSON.stringify(conJson, null, 4);
  139. fs.writeFileSync(gameJsonPath, gameJsonContent, "utf8");
  140. let gameJsPath = path.join(releaseDir, "game.js");
  141. let gameJscontent = fs.readFileSync(gameJsPath, "utf8");
  142. gameJscontent = gameJscontent.replace(/requirePlugin\("[\w\/\.]+"\);?\n?/mg, "");
  143. fs.writeFileSync(gameJsPath, gameJscontent, "utf8");
  144. }
  145. return cb();
  146. }
  147. if (config.version) {
  148. let versionPath = releaseDir + "/version.json";
  149. versionCon = fs.readFileSync(versionPath, "utf8");
  150. versionCon = JSON.parse(versionCon);
  151. }
  152. let indexJsStr = (versionCon && versionCon["index.js"]) ? versionCon["index.js"] : "index.js";
  153. // 获取version等信息
  154. let coreLibPath = path.join(workSpaceDir, "bin", "libs", "laya.core.js");
  155. let isHasCoreLib = fs.existsSync(coreLibPath);
  156. let isOldAsProj = fs.existsSync(`${workSpaceDir}/asconfig.json`) && !isHasCoreLib;
  157. let isNewTsProj = fs.existsSync(`${workSpaceDir}/src/tsconfig.json`) && !isHasCoreLib;
  158. let EngineVersion = getEngineVersion();
  159. if (!EngineVersion) {
  160. throw new Error(`读取引擎版本号失败,请于服务提供商联系!`);
  161. }
  162. if (!EngineVersion || EngineVersion.includes("beta") || !canUsePluginEngine(EngineVersion, minPluginVersion)) {
  163. throw new Error(`该版本引擎无法使用引擎插件功能(engineVersion: ${EngineVersion})`);
  164. }
  165. console.log(`通过版本号检查: ${EngineVersion}`);
  166. // 使用引擎插件
  167. let localUseEngineList = [];
  168. let copyEnginePathList;
  169. new Promise(function(resolve, reject) {
  170. console.log(`修改game.js和game.json`);
  171. // 1) 修改game.js和game.json
  172. // 修改game.js
  173. let gameJsPath = path.join(releaseDir, "game.js");
  174. let platformJs = config.useMinJsLibs ? `require("./libs/min/laya.ttmini.min.js");` : `require("./libs/laya.ttmini.js");`;
  175. let gameJscontent = `require("microgame-adapter.js");\n${platformJs}\nrequirePlugin('layaPlugin');\nwindow.loadLib = require;\nrequire("./${indexJsStr}");`;
  176. fs.writeFileSync(gameJsPath, gameJscontent, "utf8");
  177. // 修改game.json,使其支持引擎插件
  178. let gameJsonPath = path.join(releaseDir, "game.json");
  179. let gameJsonContent = fs.readFileSync(gameJsonPath, "utf8");
  180. let conJson = JSON.parse(gameJsonContent);
  181. conJson.plugins = {
  182. "layaPlugin": {
  183. "version": EngineVersion,
  184. "provider": provider,
  185. "path": "laya-libs"
  186. }
  187. }
  188. gameJsonContent = JSON.stringify(conJson, null, 4);
  189. fs.writeFileSync(gameJsonPath, gameJsonContent, "utf8");
  190. resolve();
  191. }).then(function() {
  192. return new Promise(function(resolve, reject) {
  193. console.log(`确定用到的插件引擎`);
  194. // 2) 确定用到了那些插件引擎,并将插件引擎从index.js的引用中去掉
  195. let indexJsPath = path.join(releaseDir, indexJsStr);
  196. let indexJsCon = fs.readFileSync(indexJsPath, "utf8");
  197. let item, fullRequireItem;
  198. for (let i = 0, len = fullRemoteEngineList.length; i < len; i++) {
  199. item = fullRemoteEngineList[i];
  200. fullRequireItem = config.useMinJsLibs ? `require("./libs/min/${item}")` : `require("./libs/${item}")`;
  201. if (indexJsCon.includes(fullRequireItem)) {
  202. let _item = item.replace(".min.js", ".js"), _minItem = item;
  203. localUseEngineList.push(_item);
  204. indexJsCon = indexJsCon.replace(fullRequireItem + ";", "").replace(fullRequireItem + ",", "").replace(fullRequireItem, "");
  205. // 如果引用了压缩的类库,将其重命名为未压缩的类库,并拷贝到libs中
  206. if (config.useMinJsLibs) {
  207. let oldMinlibPath = path.join(releaseDir, "libs", "min", _minItem);
  208. let newMinlibPath = path.join(releaseDir, "libs", "min", _item);
  209. let newlibPath = path.join(releaseDir, "libs", _item);
  210. fs.renameSync(oldMinlibPath, newMinlibPath);
  211. // fs.copyFileSync(newlibPath, newMinlibPath);
  212. let con = fs.readFileSync(newMinlibPath, "utf8");
  213. fs.writeFileSync(newlibPath, con, "utf8");
  214. fs.unlinkSync(newMinlibPath);
  215. }
  216. }
  217. }
  218. if (isOldAsProj || isNewTsProj) { // 如果as||ts_new语言,开发者将laya.js也写入index.js中了,将其删掉
  219. fullRequireItem = `require("./laya.js")`;
  220. if (indexJsCon.includes(fullRequireItem)) {
  221. indexJsCon = indexJsCon.replace(fullRequireItem + ";", "").replace(fullRequireItem + ",", "").replace(fullRequireItem, "");
  222. }
  223. }
  224. fs.writeFileSync(indexJsPath, indexJsCon, "utf8");
  225. // ts/js再次修改game.js,仅引用使用到的类库
  226. // as||ts_new因为本地只有laya.js,无法仅引用使用到的类库
  227. if (!isOldAsProj && !isNewTsProj) {
  228. let pluginCon = "";
  229. localUseEngineList.forEach(function(item) {
  230. pluginCon += `requirePlugin("layaPlugin/${item}");\n`;
  231. });
  232. let gameJsPath = path.join(releaseDir, "game.js");
  233. let gameJsCon = fs.readFileSync(gameJsPath, "utf8");
  234. gameJsCon = gameJsCon.replace(`requirePlugin('layaPlugin');`, pluginCon);
  235. fs.writeFileSync(gameJsPath, gameJsCon, "utf8");
  236. }
  237. resolve();
  238. });
  239. }).then(function() {
  240. return new Promise(function(resolve, reject) {
  241. console.log(`将本地的引擎插件移动到laya-libs中`);
  242. // 3) 将本地的引擎插件移动到laya-libs中
  243. let libsPath = /** config.useMinJsLibs ? `${releaseDir}/libs/min` : */`${releaseDir}/libs`;
  244. copyEnginePathList = [`${libsPath}/{${localUseEngineList.join(",")}}`];
  245. if (isOldAsProj || isNewTsProj) { // 单独拷贝laya.js
  246. copyEnginePathList = [`${releaseDir}/laya.js`];
  247. }
  248. gulp.src(copyEnginePathList).pipe(gulp.dest(`${releaseDir}/laya-libs`));
  249. setTimeout(resolve, 500);
  250. });
  251. }).then(function() {
  252. return new Promise(function(resolve, reject) {
  253. console.log(`将libs中的本地引擎插件删掉`);
  254. // 4) 将libs中的本地引擎插件删掉
  255. del(copyEnginePathList, { force: true }).then(resolve);
  256. });
  257. }).then(function() {
  258. return new Promise(async function(resolve, reject) {
  259. console.log(`完善引擎插件目录`);
  260. // 5) 引擎插件目录laya-libs中还需要新建几个文件,使该目录能够使用
  261. if (isOldAsProj || isNewTsProj) { // 单独拷贝laya.js
  262. localUseEngineList.push("laya.js");
  263. }
  264. let
  265. layalibsPath = path.join(releaseDir, "laya-libs"),
  266. engineIndex = path.join(layalibsPath, "index.js"),
  267. engineplugin = path.join(layalibsPath, "plugin.json"),
  268. enginesignature = path.join(layalibsPath, "signature.json");
  269. // index.js
  270. if (!fs.existsSync(layalibsPath)) {
  271. throw new Error("引擎插件目录创建失败,请与服务提供商联系!");
  272. }
  273. let indexCon = "";
  274. localUseEngineList.forEach(function(item) {
  275. indexCon += `require("./${item}");\n`;
  276. });
  277. fs.writeFileSync(engineIndex, indexCon, "utf8");
  278. // plugin.json
  279. let pluginCon = {"main": "index.js"};
  280. fs.writeFileSync(engineplugin, JSON.stringify(pluginCon, null, 4), "utf8");
  281. // signature.json,目前平台方将其作为保留用途,不会做插件的md5校验;IDE仍将生成md5
  282. let signatureCon = {
  283. "provider": provider,
  284. "signature": []
  285. };
  286. localUseEngineList.unshift("index.js");
  287. let fileName, md5Str;
  288. for (let i = 0, len = localUseEngineList.length; i < len; i++) {
  289. fileName = localUseEngineList[i];
  290. let md5Str = await getFileMd5(path.join(releaseDir, "laya-libs", fileName));
  291. signatureCon.signature.push({
  292. "path": fileName,
  293. "md5": md5Str
  294. });
  295. }
  296. fs.writeFileSync(enginesignature, JSON.stringify(signatureCon, null, 4), "utf8");
  297. resolve();
  298. });
  299. })
  300. .then(function() {
  301. cb();
  302. }).catch(function(e) {
  303. throw e;
  304. })
  305. });
  306. gulp.task("buildByteDanceProj", ["pluginEngin_ByteDance"], function() {
  307. console.log("all tasks completed");
  308. });