Skip to content
This repository has been archived by the owner on Apr 17, 2024. It is now read-only.

Commit

Permalink
Fix SPA serving (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
PedroHLC authored Sep 16, 2021
1 parent d2f3682 commit cd8e3b4
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 19 deletions.
58 changes: 46 additions & 12 deletions bin/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,50 @@
const path = require('path');
const ElmPlugin = require('esbuild-plugin-elm');
const EnvFilePlugin = require('./lib/env');
const http = require('http');

require('esbuild').serve(
{
servedir: 'web',
port: 1234,
},
{
entryPoints: ['web/ts/index.ts'],
outdir: 'web',
bundle: true,
plugins: [EnvFilePlugin, ElmPlugin({ debug: true })],
},
);
require('esbuild')
.serve(
{
servedir: 'web',
},
{
entryPoints: ['web/ts/index.ts'],
outdir: 'web',
bundle: true,
plugins: [EnvFilePlugin, ElmPlugin({ debug: true })],
},
)
.then((esbuildServer) => {
const { host, port } = esbuildServer;

http
.createServer((req, res) => {
const forwardRequest = (path) => {
const options = {
hostname: host,
port,
path,
method: req.method,
headers: req.headers,
};

const proxyReq = http.request(options, (proxyRes) => {
if (proxyRes.statusCode === 404) {
// If esbuild 404s the request, assume it's a route needing to
// be handled by the JS bundle, so forward a second attempt to `/`.
// https://gist.github.com/martinrue/2896becdb8a5ed81761e11ff2ea5898e
return forwardRequest('/');
}

res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});

req.pipe(proxyReq, { end: true });
};

forwardRequest(req.url);
})
.listen(1234);
});
8 changes: 4 additions & 4 deletions example/.env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env sh
ROLLBAR_TOKEN=''
AUTH0_CLIENT_ID=''
AUTH0_DOMAIN=''
AUTH0_AUDIENCE=''
export ROLLBAR_TOKEN=''
export AUTH0_CLIENT_ID=''
export AUTH0_DOMAIN=''
export AUTH0_AUDIENCE=''
2 changes: 1 addition & 1 deletion example/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
</head>
<body>
<div id="main"></div>
<script src="index.js"></script>
<script src="/index.js"></script>
</body>
</html>
2 changes: 1 addition & 1 deletion example/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


"@PaackEng/frontend-elm-kit@file:..":
version "2.1.0"
version "2.1.3"
dependencies:
elm-optimize-level-2 "^0.1.5"
esbuild "^0.12.22"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@PaackEng/frontend-elm-kit",
"version": "2.1.2",
"version": "2.1.3",
"description": "",
"private": false,
"files": [
Expand Down

0 comments on commit cd8e3b4

Please sign in to comment.