Skip to content

Instantly share code, notes, and snippets.

@fabiospampinato
Created May 23, 2021 20:21
Show Gist options
  • Save fabiospampinato/125c7a1c4ac14359f247297d840ecf50 to your computer and use it in GitHub Desktop.
Save fabiospampinato/125c7a1c4ac14359f247297d840ecf50 to your computer and use it in GitHub Desktop.
Fast building + watching + starting + restarting. AKA how to throw TypeScript in the garbage bin for anything other than type-checking.
/* IMPORT */
const esbuild = require ( 'esbuild' );
const {nodeExternalsPlugin} = require ( 'esbuild-node-externals' );
const monex = require ( 'monex' );
const path = require ( 'path' );
const {color, parseArgv} = require ( 'specialist' );
const Watcher = require ( 'watcher' );
/* HELPERS */
const args = parseArgv ();
const domains = [
'chat',
'cheatsheet',
'download',
'echo',
'img',
'plantuml',
'plantuml/server',
'status',
'telemetry',
'themes',
'tutorial'
];
const controllers = new Map ();
/* MAIN */
const notify = domain => {
console.log ( `[esbuild] ${color.bold ( domain )} - ${new Date ().toISOString ()}` );
};
const build = async domain => {
await esbuild.build ({
bundle: true,
minify: true,
platform: 'node',
target: 'es2018',
tsconfig: 'tsconfig.json',
plugins: [nodeExternalsPlugin ()],
entryPoints: [`./domains/${domain}/index.ts`],
outfile: `./dist/${domain}/index.js`
});
notify ( domain );
restart ( domain );
};
const start = domain => {
const rootPath = path.resolve ( process.cwd (), `./dist/${domain}` );
const indexPath = path.join ( rootPath, 'index.js' );
const controller = monex ({
name: domain,
exec: `node "${indexPath}"`
});
controllers.set ( domain, controller );
};
const restart = domain => {
const controller = controllers.get ( domain );
if ( controller ) return controller.restart ();
if ( !args.start ) return;
start ( domain );
};
const watch = domain => {
const rootPath = path.resolve ( process.cwd (), `./domains/${domain}` );
const ignore = filePath => /\.(?!tsx?|jsx?|json|handlebars)$/.test ( filePath );
const options = { ignoreInitial: true, recursive: true, ignore };
const rebuild = () => build ( domain );
new Watcher ( rootPath, options, rebuild );
};
const main = () => {
domains.forEach ( domain => {
build ( domain );
if ( !args.watch ) return;
watch ( domain );
});
if ( args.start || args.watch ) {
process.stdin.resume ();
}
};
main ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment