首頁 > web前端 > js教程 > 主體

FiveM x TypeScript

王林
發布: 2024-09-08 22:30:40
原創
374 人瀏覽過

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的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!