Skip to content

Instantly share code, notes, and snippets.

@dudo
Last active October 6, 2021 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudo/85cacb6dc61c42a589a1eb27b134d50f to your computer and use it in GitHub Desktop.
Save dudo/85cacb6dc61c42a589a1eb27b134d50f to your computer and use it in GitHub Desktop.
const { build } = require('esbuild');
const manifestPlugin = require('esbuild-plugin-manifest');
const options = {
entryPoints: ['src/index.js'],
entryNames: '[dir]/[name]-[hash]',
outdir: 'dist',
bundle: true,
minify: true,
plugins: [manifestPlugin()],
}
build(options).catch(() => {
process.exit(1)
})
const { serve } = require('esbuild')
const http = require('http');
const define = {}
for (const k in process.env) {
define[`process.env.${k}`] = JSON.stringify(process.env[k])
}
// Start esbuild's server on a random local port
serve({
servedir: 'dist',
}, {
// ... your build options go here ...
entryPoints: ['src/index.js'],
outdir: 'dist/js',
bundle: true,
minify: false,
sourcemap: true,
define,
}).then(result => {
// The result tells us where esbuild's local server is
const { host, port } = result
// Then start a proxy server on a custom port
http.createServer((req, res) => {
const options = {
hostname: host,
port: port,
path: req.url,
method: req.method,
headers: req.headers,
}
// Forward each incoming request to esbuild's root
const proxyReq = http.request(options, proxyRes => {
date = new Date();
console.log(`${date.toISOString()} - ${req.method} to ${req.url}`)
if (proxyRes.statusCode === 404) {
const redirectReq = http.request({ ...options, path: "/" }, (proxyRes) => {
console.log(` ↳ redirected to /`)
// Forward the response from esbuild to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
redirectReq.end();
} else {
// Forward the response from esbuild to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
}
});
// Forward the body of the request to esbuild
req.pipe(proxyReq, { end: true });
}).listen(1274);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment