FiveM x TypeScript

fivem x typescript

fivem 是 grand theft auto v 的修改版,使您能够在由 cfx.re 提供支持的定制专用服务器上玩多人游戏。

当您开发 fivem 服务器时,您可以创建资源。这些资源可以用多种语言编写:lua、c# javascript。在本文中,我们将了解如何使用 typescript 构建资源

类型 :

为了输入我们的代码,我们将使用 fivem 背后的公司 cfx.re 提供的两个软件包

  • @citizenfx/client
  • @citizenfx/服务器

这些包为客户端或服务器端代码中可用的每个本机方法提供了类型。

tsconfig.json

{
  "compileroptions": {
    "target": "es2020",
    "module": "esnext",
    "moduleresolution": "bundler",
    // location
    "outdir": "./dist",
    // other
    "types": ["@citizenfx/client", "@types/node"],
    "lib": ["es2020"],
    "strict": true,
    "esmoduleinterop": true,
    "allowsyntheticdefaultimports": true,
    "skiplibcheck": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["**/node_modules", "**/.test.ts"]
}

捆 :

编译 .ts 文件后,您将必须创建一个将由 fivem 服务器加载和运行的包。事实上,fivem 只允许 require 原生 node.js 包,如路径、fs、…

为此,我们使用名为 rollup 的工具,它是一个基于插件系统的 javascript 模块捆绑器。我也探索过其他工具,如 vite、rspack,但太复杂了。另一种提供良好性能的工具是turbopack,它是下一次捆绑之后的工具,但目前仍然在下一次。

rollup.config.mjs

import typescript from "@rollup/plugin-typescript";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";

export default {
  input: "src/index.ts",
  output: {
    dir: "dist",
    format: "cjs",
    sourcemap: false,
  },
  plugins: [resolve(), typescript(), commonjs()],
};

package.json :

{
  ...
  "devdependencies": {
    "@citizenfx/client": "2.0.9282-1",
    "@rollup/plugin-commonjs": "^26.0.1",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-typescript": "^11.1.6",
    "@types/node": "^20.14.12",
    "rollup": "^4.20.0",
    "tslib": "^2.6.3",
    "typescript": "^5.5.4"
  },
  ...
}

示例

init.ts

import { join } from "path"

export const init = () => {
    console.log("inited", join(".", "init.js"));
}

index.ts

import { init } from "./init"

on("onresourcestart", async (resname: string) => {
  if (resname === getcurrentresourcename()) {
    init();
  }
});

运行 rollup -c 后,您将只有一个文件:

'use strict';

var path = require('path');

const init = () => {
    console.log("inited", path.join(".", "init.js"));
};

on("onResourceStart", async (resName) => {
    if (resName === GetCurrentResourceName()) {
        init();
    }
});

以上就是FiveM x TypeScript的详细内容,更多请关注www.sxiaw.com其它相关文章!