import chokidar from 'chokidar'; import fs from 'fs'; import fse from 'fs-extra'; import esbuild from 'esbuild'; // ==================================================================== // | // ==================================================================== function log(message) { const options = { encoding: 'utf-8', flag: 'a+', }; const datetime = new Date().toISOString(); message = `[${datetime}] ${message}\n`; fse.outputFileSync( '/logs/builder/javascript.log', message, options ); console.log(message); } // ==================================================================== // | // ==================================================================== async function buildJavascript(path) { var jsFolder = path; jsFolder = jsFolder.split("/")[3]; const outfile = `/www/js/${jsFolder}.js` const filename = path.split("/").slice(-1).toString() const entryPoint = path.replace(filename, 'index.js') log(`Building ${filename}`); log(`Entry: ${entryPoint}`); log(`Output: ${outfile}`); await esbuild.build({ entryPoints: [entryPoint], bundle: true, outfile, format: 'esm', sourcemap: true, target: ['es2022'], logLevel: 'info' }); log(`Finished ${filename}`); } // ==================================================================== // | // ==================================================================== async function compileAll() { const folders = fs .readdirSync('/app/js', { withFileTypes: true }) .filter(entry => entry.isDirectory()) .map(entry => entry.name); for (const folder of folders) { const entryPoint = `/app/js/${folder}/index.js`; if (!fs.existsSync(entryPoint)) { continue; } await buildJavascript(`/app/js/${folder}/index.js`); } log('Done'); } // ==================================================================== // | // ==================================================================== function startWatcher(watchFolders) { const options = { awaitWriteFinish: true, ignoreInitial: true, usePolling: true, interval: 100 }; const watcher = chokidar.watch( watchFolders, options ); watcher.on('all', async (event, filePath) => { log(`${event}: ${filePath}`); try { await buildJavascript(filePath); } catch (error) { log(`Build failed: ${error.message}`); } }); watcher.on( 'ready', () => log('********** Watch is running **********') ); } // ==================================================================== // | MAIN // ==================================================================== async function go() { const watchFolders = [ '/app/js' ]; if (process.argv[2] === 'compile-and-watch') { await compileAll(); startWatcher(watchFolders); } else if (process.argv[2] === 'compile-only') { await compileAll(); } else { startWatcher(watchFolders); } } go();