One repetitive task often disrupts you when you developing your FiveM resource: the resource reloading.
Indeed each time you make a change to your code, you need to run restart <resName>
in the FiveM console inside the game. This process, while functional, is a time sink that adds up, especially when working on complex projects.
Wouldn't it be great if FiveM development could adopt a similar hot-reload mechanism of webapp? Let’s dive into the problem and explore how to create a hot-reload solution.
Conception
To run restart <resName>
command, we can use the method ExecuteCommand
provided by FiveM inside resource scripts. We also need an entry point to trigger this restart. In my side, I choose an http server (but other type of server can work).
My JS Hot-reload source code
I did it in JS because it's my main language but you can do it with Lua or C#.
TAKE CARE: Give the right permissio needed to run restart command //todo
const http = require("http");
// Set the port for the HTTP server
const PORT = 3000;
// Create the HTTP server
const server = http.createServer((req, res) => {
console.log("url", req.url);
if (req.method !== "POST" || !req.url?.startsWith("/restart?resource=")) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Invalid request");
return;
}
const resource = new URLSearchParams(req.url.split("?")[1]).get("resource");
console.log("Resource to restart:", resource);
if (resource !== "hot-reload") {
ExecuteCommand(`restart ${resource}`);
}
// Handle the response
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Resource restarted");
});
// Start the server
server.listen(PORT, "0.0.0.0", () => {
console.log(`HTTP Server running on port ${PORT}`);
});
How to detect when trigger hot-reload
For people using Javascript or Typescript, I assume you have a bundler tool like explained in this article
You can easily create a custom plugin to do it
function pluginTriggerFivemResourceRestart() {
return {
name: "trigger-fivem-resource-restart", // Name of the plugin
closeBundle() {
const resourceName = "<resName>"
// Restart the resource by make a POST request with JSON data
fetch(`http://localhost:3000/restart?resource=${resourceName}`, {
method: "POST",
});
},
};
}
For lua resource, a simple "watcher" like glob-watcher to check changes for *.lua
files and run fetch request on change is "sufficient"
To go further
If you are in PNPM workspace with multiple typescript resources dependent on each other, you will find a way to create an efficient watch mode to automize dependencies rebuild.
Top comments (0)