[LayaAir 2.0]深入理解LayaAir引擎架构和实现原理(一)跨平台引擎源码编译

拉取引擎源码
LayaAir查看目录结构
  
 
laya引擎是使用TypeScript开发的,引擎核心代码在src/LayaAir路径下,查看tsconfig.json文件可知其编译目标环境为es6。编译引擎代码
项目路径下
[code]npm i
复制代码
[/code]
安装所需依赖库
查看package.json中的命令,会发现它的编译命令build是去执行public.bat,我觉得这个不行,引擎开发人员没有完成macOS环境下的编译,所以我们自己加个支持跨平台的编译命令crossBuild。
[code]  "scripts": {
"build": "cd src/publishTool&&cmd /k publish.bat",
"compile": "gulp LayaAirBuild",
"buildDoc": "cd src/generateDoc&&cmd /k run.bat",
"crossBuild": "node src/publishTool/publish.js && cd src && gulp build"
},
复制代码
[/code]
src/publishTool路径下创建publish.js。编译工具public.bat中做了什么事情,在publish.js脚本中也做同样的事情就好。
public.bat
[code]@echo off
if exist ..\..\build (
rmdir /s/q ..\..\build
)

if exist ..\..\bin\tsc\layaAir (
rmdir /s/q ..\..\bin\tsc\layaAir
)
node index.js

cd ..\
gulp build

@pause
复制代码
[/code]
查看代码易知,在编译前,会先删除build和 bin/tsc/layaAir文件夹。build文件夹是最终导出各语言平台下laya引擎库文件的地方。layaAir文件夹是引擎项目tsc编译的导出目录。AS语言的引擎库文件就是根据该目录下的文件转换的。
之后会执行index.js文件,先来看看入口函数start()
[code]    start() {
return __awaiter(this, void 0, void 0, function* () {
let json = JSON.parse(fs.readFileSync("outConfig.json"));
this.BaseURL = emiter_1.emiter.BaseURL = json.from;
this.outfile = json.out;
this.createAS = json.createAS;
this.layajsURL = json.layajsURL;
this.tsCongfig = json.tsConfig;
this.filterArr = json.filter;
emiter_1.emiter.jscObj = json.jscObj;
// yield相当于await
if (!this.tsCongfig.length || (yield this.compile())) { //确认编译结果
this.checkAllDir("");
}
else {
console.log("compile fail!");
}
});
}
复制代码
[/code]
其中__awaiter是一个编译工具函数,相当于async/await ,因为引擎项目是ES6的,所以使用这种方式实现异步执行的功能,想进一步了解的可以看这里
编译的配置在outConfig.json中,其中有个是否导出AS的开关createAS,不需要就可以关闭了,加快编译速度。
编译函数compile(),它的功能是根据配置去执行tsc编译,但是这边它直接用局部的tsc.cmd去执行,并且也写的不好,所以我们把他改成更通用的方式。
[code]                let cmd = ["-b", tsConfigUrl];
let tscurl = path.join(this.BaseURL.split("bin")[0], "./node_modules/.bin/tsc.cmd");
child_process.execFile(tscurl, cmd, (err, stdout, stderr) => {
if (err) {
console.log(err, '\n', stdout, '\n', stderr);
}
start(err);
});
复制代码
[/code]
改为
[code]                let cmd = "tsc -b " + tsConfigUrl;
child_process.exec(cmd, (err, stdout, stderr) => {
if (err) {
console.log(err, '\n', stdout, '\n', stderr);
}
start(err);
});
复制代码
[/code]
准备妥当开始编写public.js
[code]var fs = require('fs'); // 引入fs模块
var path = require('path');
const child_process = require("child_process");

function deleteall(path) {
// lear
var files = [];
if(fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function(file, index) {
var curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()) {
deleteall(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};

let buildPath = path.join(__dirname,'../../build')
deleteall(buildPath);

let layaAirPath = path.join(__dirname,'../../bin/tsc/layaAir')
deleteall(layaAirPath);

process.chdir(__dirname);
require('./index.js');
复制代码
[/code]
项目路径下执行
[code]npm run crossBuild
复制代码
[/code]
即可实现Windows/macOS系统下LayaAir引擎的编译。
已邀请:

要回复问题请先

商务合作
商务合作