Skip to content

Instantly share code, notes, and snippets.

@kevinfiol
Created November 29, 2022 04:12
Show Gist options
  • Save kevinfiol/2bd7f33069cf76a7d999593d36ab9b80 to your computer and use it in GitHub Desktop.
Save kevinfiol/2bd7f33069cf76a7d999593d36ab9b80 to your computer and use it in GitHub Desktop.
import servbot from 'servbot';
import esbuild from 'esbuild';
import env from 'env-smart';
import { writeFile } from 'fs/promises';
import { resolve } from 'path';
// load .env file variables
env.load();
const DEV = process.argv.includes('-d');
const API_URL = process.env.API_URL;
const ENTRY = 'src/index.js';
const OUTDIR = 'dist/js';
const SERVER_PORT = 8081;
function logSuccess() {
console.log('\x1b[42m%s\x1b[0m', `Bundled: ${OUTDIR}`);
}
function logError(msg) {
console.error('\x1b[41m%s\x1b[0m', msg)
}
function bundle(config = {}) {
return esbuild.build({
minify: true,
format: 'esm',
entryPoints: [resolve(ENTRY)],
outdir: resolve(OUTDIR),
bundle: true,
splitting: true,
metafile: true,
jsxFactory: 'm',
jsxFragment: '"["',
define: {
'process.env.API_URL': `"${API_URL}"`
},
...config
}).then(({ metafile }) =>
writeFile(
resolve(OUTDIR + '/meta.json'),
JSON.stringify(metafile),
{ encoding: 'utf-8' }
)
);
}
let config = {minify:false};
if (DEV) {
const server = servbot({
root: 'dist',
reload: true,
fallback: 'index.html'
});
server.listen(SERVER_PORT);
config = {
minify: false,
sourcemap: true,
watch: {
onRebuild(error) {
if (error) logError(error);
else {
logSuccess();
server.reload();
}
}
}
};
}
bundle(config)
.then(logSuccess)
.catch((error) => {
logError(error);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment