如何编写一个简单的TypeScriptToLua lua 模块定义包
以下主要说明下简单的编写,对于复杂的后续会介绍(以为lua 语言的特殊性,部分需要依赖其他类型)
一个案例
比如我们有一个lua 模块,包装一个平台认证服务(为了方便openresty 使用的,基于lua+c 开发的)
我们为了方便大家开发方便,提供了基于TypeScriptToLua 的定义包,这样前端同学也就可以方便的编写lua 模块了
- 参考lua接口定义
假如我们约定我们的模块名称为platformlogin
local function loginv1(name,password)
--- code
end
local function logoutv1()
--- code
end
return {
login = loginv1,
logout = logoutv1
}
参考ts 包开发
- package.json
{
"name": "@dalongrong/platform-login",
"version": "1.0.1",
"types": "platform-login.d.ts",
"files": [
"*.d.ts"
],
"license": "MIT",
"scripts": {
"p": "yarn publish"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.com"
}
}
platform-login.d.ts
基于以上的约定我们使用了module,实际上也是可以直接使用namespace的(而且很多时候直接使用namespace 是不错的选择)
/** @noSelfInFile */
declare module "platformlogin" {
type opResult = 0 |1
function login(name:string,password):string
function logout():opResult
}
ts 项目引用开发的模块定义
- package.json
{
"name": "mylogin-ts",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "tstl",
"dev": "tstl --watch"
},
"devDependencies": {
"@dalongrong/platform-login": "^1.0.2",
"typescript": "^4.6.3",
"typescript-to-lua": "^1.4.3"
}
}
- tsconfig.json
{
"tstl": {
"luaTarget": "JIT",
"noHeader":true,
"noImplicitSelf":true,
"buildMode": "library",
"noResolvePaths":["platformlogin"] // 忽略引用包的解析,因为是原生lua 模块
},
"compilerOptions": {
"types": ["@dalongrong/platform-login"], // 类型定义
"target": "es2016",
"outDir": "dist",
"module": "commonjs", /* Specify what module code is generated. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
- 代码集成
import * as demo from "platformlogin"
let token = demo.login("name","password")
console.log(token)
- 使用效果
说明
以上是一个简单的开发说明,比较简单,但是可以参考,有助于基于ts开发高效的lua 模块
参考资料
https://github.com/TypeScriptToLua/lua-types
https://github.com/andrei-markeev/openresty-lua-type
https://typescripttolua.github.io/
https://typescripttolua.github.io/docs/advanced/writing-declarations