Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCatalin Mititiuc <webdevcat@proton.me>2024-05-29 18:01:24 -0700
committerCatalin Mititiuc <webdevcat@proton.me>2024-05-29 18:01:24 -0700
commitfdf9e0145ee14d4db7004c56d0e5b15cb3461e2d (patch)
treef2feca42050d8493cfb9bae42966a0afb222b99f
parent7e5aedeb0a1ffa727005c98d80044429bf20ff45 (diff)
Refactor esbuild server file
-rw-r--r--esbuild-server.mjs117
1 files changed, 58 insertions, 59 deletions
diff --git a/esbuild-server.mjs b/esbuild-server.mjs
index 3d9b0ca..01629d1 100644
--- a/esbuild-server.mjs
+++ b/esbuild-server.mjs
@@ -3,6 +3,8 @@ import * as fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
+const __dirname = path.dirname(new URL(import.meta.url).pathname);
+
const colors = {
reset: '\x1b[0m',
dim: '\x1b[2m',
@@ -11,9 +13,15 @@ const colors = {
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
-}
+};
-let version;
+const mime = {
+ '.svg': 'image/svg+xml; charset=utf-8',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.css': 'text/css; charset=utf-8',
+ '.html': 'text/html; charset=utf-8',
+};
const importSvg = {
name: 'importSvg',
@@ -100,16 +108,30 @@ const svgUseCacheBust = {
}
};
-const paths = ['/esbuild', '/index.js', '/map.js', '/soldier_record_block.js'];
+const resolveImportedSvg = {
+ name: 'resolveImportedSvg',
+ setup(build) {
+ build.onStart(() => {
+ console.log("BUILD STARTED");
+ });
+
+ build.onResolve({ filter: /\.svg$/ }, args => {
+ return {
+ path: path.resolve('public', args.path),
+ };
+ });
+ }
+}
const ctx = await esbuild.context({
entryPoints: ['src/*.js'],
bundle: true,
outdir: 'build',
- plugins: [svgUseCacheBust, importSvg],
+ plugins: [resolveImportedSvg],
loader: {
'.svg': 'file'
},
+ assetNames: 'assets/images/[name]-[hash]',
});
await ctx.watch();
@@ -117,17 +139,17 @@ await ctx.watch();
const { host, port } = await ctx.serve({
servedir: 'build',
port: 3000,
- onRequest: function({ remoteAddress, method, path, status, timeInMS }) {
- let statusColor = colors.red;
+ // onRequest: function({ remoteAddress, method, path, status, timeInMS }) {
+ // let statusColor = colors.red;
- if (status >= 200 && status <= 299) {
- statusColor = colors.green;
- } else if (status >= 300 && status <= 399) {
- statusColor = colors.yellow;
- }
+ // if (status >= 200 && status <= 299) {
+ // statusColor = colors.green;
+ // } else if (status >= 300 && status <= 399) {
+ // statusColor = colors.yellow;
+ // }
- console.log(`${colors.dim}${remoteAddress} - "${method} ${path}" ${colors.normal}${statusColor}${status}${colors.reset}${colors.dim} [${timeInMS}ms]${colors.reset}`);
- },
+ // console.log(`${colors.dim}${remoteAddress} - "${method} ${path}" ${colors.normal}${statusColor}${status}${colors.reset}${colors.dim} [${timeInMS}ms]${colors.reset}`);
+ // },
});
http.createServer((req, res) => {
@@ -139,55 +161,32 @@ http.createServer((req, res) => {
headers: req.headers,
}
- if (paths.includes(req.url)) {
- const proxyReq = http.request(options, proxyRes => {
- for (const k in proxyRes.headers) {
- res.setHeader(k, proxyRes.headers[k]);
- }
-
- res.writeHead(proxyRes.statusCode, { 'Cache-Control': 'no-cache, no-store, must-revalidate' });
-
- proxyRes.pipe(res, { end: true });
- })
-
- return req.pipe(proxyReq, { end: true });
- }
-
- console.log(host, port, req.method, req.url, res.statusCode);
-
- const serverUrl = `http://localhost:${port}`;
- const url = new URL(`${serverUrl}${req.url}`);
- const dir = 'public';
-
- const filePath = path.normalize(
- path.join(dir, url.pathname === '/' ? 'index.html' : url.pathname)
- );
-
- console.log('filepath', filePath);
+ const filename = req.url && req.url !== '/' ? req.url : 'index.html';
+ const filepath = path.join(__dirname, 'public', filename);
- for (const k in res.headers) {
- res.setHeader(k, res.headers[k]);
- }
+ if (fs.existsSync(filepath)) {
+ const readStream = fs.createReadStream(filepath, { autoClose: true });
- let contentType;
+ readStream.on('ready', () => {
+ const type = mime[path.parse(filepath).ext] || 'application/octet-stream';
+ console.log(`${req.method} ${req.url} => 200 ${type}`);
+ res.writeHead(200, { 'content-type': type });
+ readStream.pipe(res, { end: true });
+ });
- if (req.url.endsWith('.svg')) {
- contentType = 'image/svg+xml';
- } else if (req.url.endsWith('.png')) {
- contentType = 'image/png';
- } else if (req.url.endsWith('.jpg')) {
- contentType = 'image/jpeg';
- } else if (req.url.endsWith('.css')) {
- contentType = 'text/css';
+ readStream.on('error', err => {
+ console.log(`${req.method} ${req.url} => 500 ${filepath} ${err.name}`);
+ res.writeHead(500, err.name);
+ res.end(JSON.stringify(err));
+ });
} else {
- contentType = 'text/html';
- }
-
- res.writeHead(res.statusCode, {
- 'Cache-Control': 'no-cache, no-store, must-revalidate',
- 'Content-Type': contentType
- });
+ const proxyReq = http.request(options, proxyRes => {
+ const type = proxyRes.headers['content-type'];
+ console.log(`${req.method} ${req.url} => ${proxyRes.statusCode} ${type} via esbuild`);
+ res.writeHead(proxyRes.statusCode, { 'content-type': type });
+ proxyRes.pipe(res);
+ });
- const readStream = fs.createReadStream(filePath, { autoClose: true });
- readStream.pipe(res, { end: true });
+ req.pipe(proxyReq, { end: true });
+ }
}).listen(8080);