Introduction
The official PuerTS project tends to leave project-specific mechanisms to each project team, and it does not provide more general best practices.
However, when putting it into practice in a project, concrete solutions are still needed to implement the relevant requirements, so here I summarize some best practices from my own practical use of PuerTS.
You can also refer to: PuerTS Template Project for Unreal Engine (UE5)
Virtual Machine Environment
The official project provides the inherit-engine-class feature, which must be enabled by setting Enable in Project Settings-Plugins-Puerts Settings. With this, after the engine starts, Puerts automatically starts a JavaScript virtual machine environment. The plugin monitors changes to TypeScript files; if a qualifying TypeScript class exists, it automatically generates the corresponding Blueprint file, and when that Blueprint is called at runtime it can invoke the logic in the corresponding JavaScript class.
However, the official recommendation now is to manage the virtual machine environment yourself, that is, to create a JavaScript virtual machine environment via MakeShared<puerts::FJsEnv> at an appropriate time. By creating the virtual machine environment yourself, you can specify a ModuleName, and after the virtual machine starts it runs the JavaScript file corresponding to that ModuleName. With this approach, you also need to handle the binding between Blueprints and JavaScript classes yourself.
Automatic Binding
The official project provides two ways to associate Blueprints with JavaScript classes:
- Inherit engine class
- Mixin
The official recommendation favors calling Mixin manually, to avoid a large amount of cross-language interaction between Blueprints and JavaScript classes caused by overuse of inheriting engine classes.
However, for a project’s concrete use cases, having every developer manually call a Blueprint’s Mixin function may not be realistic. For my project, a method similar to Unlua—specifying the relationship between a Blueprint and a TS class—was preferable, so I wrote a plugin that automatically binds JavaScript classes: BoilTask/PuertsAutoMixin.
This plugin works by having a Blueprint inherit PuertsInterface, then overriding the GetJavaScriptModule function to specify the associated JavaScript class. Most of the time, the path automatically generated by the plugin is sufficient; if you need to specify a class, you can also modify it manually.
After the virtual machine starts, call the BindMixin function to associate the JavaScript class.
1
2
3
4
| void UMetaGameInstance::BindMixin(const FPuertsAutoMixinDelegate& BindCallback)
{
UPuertsAutoMixinSubsystem::GetInstance().RegisterBindDelegate(JsEnv, BindCallback);
}
|
1
2
| let gameInstance = argv.getByName("GameInstance") as UE.MetaGameInstance;
gameInstance.BindMixin(toDelegate(gameInstance, ToMinix))
|
Auto-generating JavaScript Files
Using tsc Directly
You can add a generation task using TypeScript’s native tsc --watch command, starting tsc to watch for file changes and automatically generate the corresponding JavaScript files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| {
"label": "tsc: 监视 - tsconfig.json (大内存)",
"type": "shell",
"command": "node",
"args": [
"--max-old-space-size=8192",
"./node_modules/typescript/bin/tsc",
"--watch",
"-p",
"tsconfig.json"
],
"problemMatcher": [
"$tsc-watch"
],
"group": {
"kind": "build",
"isDefault": true
}
}
|
Using Vite to Manage the Build Process
Refer to the vite.config.ts file in the PuerTS Template Project for Unreal Engine (UE5).
Hot Reload HotReload
Refer to the solution mentioned in Need code “hot reload” functionality; it can automatically reload JavaScript classes after code changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| void UMetaGameInstance::StartJavaScriptEnv()
{
#if WITH_EDITOR
std::function<void(const FString&)> SourceLoadedCallback = nullptr;
SourceFileWatcher = MakeShared<PUERTS_NAMESPACE::FSourceFileWatcher>(
[this](const FString& InPath)
{
HotReloadJavaScriptEnv(InPath);
});
SourceLoadedCallback = [this](const FString& InPath)
{
if (SourceFileWatcher.IsValid())
{
SourceFileWatcher->OnSourceLoaded(InPath);
}
};
#endif
JsEnv = MakeShared<puerts::FJsEnv>(std::make_unique<puerts::DefaultJSModuleLoader>(
TEXT("JavaScript")
)
, std::make_shared<puerts::FDefaultLogger>()
, 8080
, SourceLoadedCallback
);
TArray<TPair<FString, UObject*>> Arguments;
Arguments.Add(TPair<FString, UObject*>(TEXT("GameInstance"), this));
// JsEnv->WaitDebugger();
JsEnv->Start("QuickStart", Arguments);
}
void UMetaGameInstance::HotReloadJavaScriptEnv(const FString& Path)
{
if (JsEnv.IsValid())
{
TArray<uint8> Source;
if (FFileHelper::LoadFileToArray(Source, *Path))
{
LOG_CATEGORY_INFO(Puerts, "start ReloadSource %s", *Path);
JsEnv->ReloadSource(Path, puerts::PString((const char*)Source.GetData(), Source.Num()));
LOG_CATEGORY_INFO(Puerts, "end ReloadSource %s", *Path);
}
else
{
UE_LOG(Puerts, Error, TEXT("read file fail for %s"), *Path);
}
}
}
|
Logging Extensions
From JavaScript to TypeScript
You can use source-map and source-map-support to map information from JavaScript back to TypeScript.
Because this does not use a nodejs environment but the v8 engine, you need to manually register the path and fs modules using file operation functions wrapped by the project itself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| /**
* 获取文件所在目录路径
*/
FString UPlatformLibrary::GetDirectoryName(const FString& Path)
{
return FPaths::GetPath(Path);
}
/**
* 合并路径
*/
FString UPlatformLibrary::CombinePath(const FString& Directory, const FString& File)
{
return FPaths::Combine(Directory, File);
}
/**
* 检查文件是否存在
*/
bool UPlatformLibrary::FileExists(const FString& Path)
{
return FPaths::FileExists(Path);
}
/**
* 读取文件所有文本内容
*/
FString UPlatformLibrary::ReadAllText(const FString& Path)
{
if (!FPaths::FileExists(Path))
{
LOG_CATEGORY_WARN(LogMetaSystem, "File not exists, Path:{}", Path);
return FString();
}
FString Result;
if (FFileHelper::LoadFileToString(Result, *Path))
{
return Result;
}
LOG_CATEGORY_ERROR(LogMetaSystem, "Read file failed, Path:{}", Path);
return FString();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| import * as UE from "ue";
var puerts = require("puerts");
puerts.registerBuildinModule("path", {
dirname(path) {
return UE.PlatformLibrary.GetDirectoryName(path);
},
resolve(dir, url) {
url = url.replace(/\\/g, "/");
while (url.startsWith("../")) {
dir = UE.PlatformLibrary.GetDirectoryName(dir);
url = url.substr(3);
}
return UE.PlatformLibrary.CombinePath(dir, url);
},
});
puerts.registerBuildinModule("fs", {
existsSync(path) {
return UE.PlatformLibrary.FileExists(path);
},
readFileSync(path) {
return UE.PlatformLibrary.ReadAllText(path);
},
});
(function () {
let global = this ?? globalThis;
global["Buffer"] = global["Buffer"] ?? {};
})();
require('source-map-support').install();
|
You can include the currently called TypeScript file name and line number when outputting logs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
| const originalLog = console.log;
// 解析调用者信息
function getCallerInfo() {
const stack = new Error().stack;
if (!stack) return null;
// 获取调用者行(跳过前两行:Error构造函数和getCallerInfo本身)
const stackLines = stack.split("\n");
const callerLine = stackLines[3]; // 第4行才是真正的调用者
if (!callerLine) return null;
// 解析函数名和位置信息
// 匹配格式:at functionName (filePath:line:column)
// 或者:at filePath:line:column (匿名函数)
const match = callerLine.match(/at\s+(?:([^\s(]+)\s+)?\(([^)]+)\)|at\s+([^\s]+)/);
if (!match) return null;
let functionName = match[1] || "anonymous";
let location = match[2] || match[3];
// 简化函数名,特别是UE5蓝图相关的函数名
// 对于格式如 /Game/Path/Blueprint.Blueprint_C.FunctionName 的函数名,只保留FunctionName
if (functionName.includes(".")) {
const parts = functionName.split(".");
functionName = parts[parts.length - 1];
}
// 对于格式如 ClassName::FunctionName 的函数名,保留 ClassName::FunctionName
// 对于匿名函数,保持原样
if (!location) return null;
// 尝试从位置信息中解析文件路径和行号
// 对于TypeScript项目,位置信息可能包含源映射信息
// 格式可能是:file.js:line:column
const locationMatch = location.match(/^(.*):(\d+):(\d+)$/);
if (!locationMatch) return null;
const filePath = locationMatch[1];
const lineNumber = locationMatch[2];
// 尝试从filePath中提取TypeScript源文件信息
// 如果启用了source map,可能需要额外处理
// 这里简单地尝试将JavaScript路径转换为TypeScript路径
// 只保留文件名部分
const fileName = filePath.split(/[\\/]/).pop() || filePath.split(/[\\/]/).pop() || "unknown";
return {
functionName,
fileName,
lineNumber,
};
}
console.log = function (...args: any[]) {
const callerInfo = getCallerInfo();
if (callerInfo) {
args.unshift(`[${callerInfo.fileName}:${callerInfo.lineNumber}:${callerInfo.functionName}]`);
}
// 将多个参数合并成一个字符串,用空格分隔,避免底层库使用逗号分隔
const combinedArgs = args.map((arg) => String(arg)).join("\t");
originalLog.apply(console, [combinedArgs]);
};
|
The same applies to console.info and console.warn; for console.error, the caller stack is also output.
1
2
3
4
5
6
7
8
9
10
11
12
| console.error = function (...args: any[]) {
const callerInfo = getCallerInfo();
if (callerInfo) {
args.unshift(`[${callerInfo.fileName}:${callerInfo.lineNumber}:${callerInfo.functionName}]`);
}
// 将多个参数合并成一个字符串,用空格分隔,避免底层库使用逗号分隔
const combinedArgs = args.map((arg) => String(arg)).join("\t");
// 获取完整的堆栈信息
const stack = new Error().stack;
const errorOutput = stack ? `${combinedArgs}\n${stack}` : combinedArgs;
originalError.apply(console, [errorOutput]);
};
|
You can use JavaScript’s prototype mechanism to adjust the default toString method used by a type when outputting logs.
1
2
3
4
5
| import * as UE from "ue";
UE.Vector2D.prototype.toString = function () {
return `(${this.X}, ${this.Y})`;
};
|
Configuration Reference
The core of package.json consists of typescript, eslint, source-map, and so on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| {
"name": "metagame",
"version": "1.0.0",
"description": "UE5项目",
"main": "index.js",
"scripts": {
"format": "prettier --write .",
"lint": "eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@rushstack/eslint-patch": "^1.11.0",
"@types/node": "^16.11.56",
"eslint": "^8.22.0",
"prettier": "^3.3.2",
"typescript": "^5.5.4"
},
"dependencies": {
"source-map": "^0.7.6",
"source-map-support": "^0.5.21"
}
}
|
The tsconfig.json configuration is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| {
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"experimentalDecorators": true,
"jsx": "react",
"sourceMap": true,
"inlineSources": true,
"typeRoots": [
"Typing",
"./node_modules/@types"
],
"outDir": "Content/JavaScript"
},
"include": [
"TypeScript/**/*"
],
}
|