首先,创建一个新的目录并初始化 npm 项目:
mkdir lua-client
cd lua-client
yarn init -y
安装 TypeScript 和其他依赖
yarn add typescript @types/node --dev
yarn add @msgpack/msgpack
配置 TypeScript 编译器
{
"compilerOptions": {
"outDir": "./dist",
"module": "commonjs",
"target": "ES2020",
"strict": true,
"declaration": true,
"declarationMap": true,
"lib": [
"ES2020",
"dom"
]
},
"include": ["src"]
}
在 package.json
中添加编译脚本
配置字段 main types scripts files
{
"name": "lua-client",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc"
},
"files": [
"dist"
],
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"typescript": "^5.5.2"
},
"dependencies": {
"@msgpack/msgpack": "^3.0.0-beta2"
}
}
创建源代码目录和文件
这里参考 如何 export 导出 变量 函数 类
src/index.ts
import axios from 'axios';
// 公开的变量
export const myVariable = 'Hello, World!';
// 公开的函数
export function myFunction(name: string): string {
return `Hello, ${name}!`;
}
// 公开的类
export class MyClass {
private myProperty: string;
constructor(myProperty: string) {
this.myProperty = myProperty;
}
// 类的方法必须是public
public myMethod(): string {
return `My property value is: ${this.myProperty}`;
}
public async fetchData(url: string): Promise<any> {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
throw new Error('Error fetching data');
}
}
}
运行编译命令
yarn build
构建一个依赖包
会在当前项目下产生一个压缩包
F:\workspace\tauri\lua-client\lua-client-v1.0.0.tgz
yarn pack
在其他项目引入本地包
yarn add F:\\workspace\\tauri\\lua-client\\lua-client-v1.0.0.tgz
yarn install