async function root() {
const loader = {
'.js': 'jsx', ".css": "css",
'.woff': 'file', '.woff2': 'file', '.ttf': 'file', '.eot': 'file', '.otf': 'file',
'.png': 'file', '.jpg': 'file', '.jpeg': 'file', '.gif': 'file',
'.gltf': 'file', '.glb': 'file', '.bin': 'file',
};
if (development) {
const httpCache = {};
const staticRegistry = {};
async function rebuild(filepath) {
console.info('Change detected:', filepath);
const result = await ctx.rebuild();
hostProject(result.outputFiles, httpCache, staticRegistry) ;
}
async function cacheFile(filepath) {
const name = path.basename(filepath);
httpCache[name] = await fsExtra.readFile(filepath);
staticRegistry[name] = 1;
}
function purgeFile(filepath) {
const name = path.basename(filepath);
delete httpCache[name];
delete staticRegistry[name];
}
const ctx = await esbuild.context({
entryNames: 'bundle',
assetNames: '[name]-[hash]',
entryPoints: [entry],
outdir: outdir,
write: false,
bundle: true,
splitting: true,
format: 'esm',
logLevel: 'error',
loader: loader,
});
const result = await ctx.rebuild();
hostProject(result.outputFiles, httpCache, staticRegistry) ;
const buildWatcher = chokidar.watch(srcdir, {
persistent: false,
ignoreInitial: true,
depth: Infinity,
})
.on('add', rebuild)
.on('change', rebuild)
.on('unlink', rebuild)
.on('addDir', rebuild)
.on('unlinkDir', rebuild);
const staticWatcher = chokidar.watch(stcdir, {
persistent: false,
ignoreInitial: false,
depth: 0
})
.on("add", cacheFile)
.on("change", cacheFile)
.on("unlink", purgeFile)
.on("error", error => console.error("Error:", error));
const server = uWS.App()
.get('/*', (res, req) => {
const file = httpCache[req.getUrl().slice(1) || "index.html"];
if (!file) { res.close(); return; }
res.writeHeader('Content-Type', file.type);
res.end(file.buffer);
}).listen(port, token => {
if (token) {
console.log(`Development server run at: http://localhost:${port}`);
} else {
console.log("Development server error.");
}
});
async function shutdown() {
server.close();
await ctx.dispose();
await buildWatcher.close();
await staticWatcher.close();
console.log("Shutdown");
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
process.on('SIGQUIT', shutdown);
process.on('SIGBREAK', shutdown);
} else {
await fsExtra.emptyDir(outdir);
const result = await esbuild.build({
entryNames: 'bundle',
assetNames: '[hash]',
entryPoints: [entry],
outdir: outdir,
write: false,
loader: loader,
logLevel: 'error',
});
if (result.errors.length > 0) {
for (const error of result.errors) {
console.error("Error:", error);
}
if (!development) {
process.exit(1);
}
} else {
buildProject(result.outputFiles);
}
}