Skip to content

Instantly share code, notes, and snippets.

@kasper573
Created January 5, 2018 14:58
Show Gist options
  • Save kasper573/b4eb6f8f562be6f4f04223bcfe4a5ad4 to your computer and use it in GitHub Desktop.
Save kasper573/b4eb6f8f562be6f4f04223bcfe4a5ad4 to your computer and use it in GitHub Desktop.
import * as express from 'express';
import * as path from 'path';
import * as args from 'args';
import * as fs from 'fs';
import {BuildInjects} from '../BuildOptions';
args
.option('dist', 'The path to the folder to distribute', path.join(__dirname, '../dist'))
.option('port', 'The port on which the server will be running')
.option('host', 'The host on which the server should listen');
// Add injects to CLI
const cliBuildInjects = new BuildInjects();
const injectKeys = Object.keys(cliBuildInjects);
injectKeys.forEach((key) => args.option(key, key));
const cliArgs = args.parse(process.argv);
// Get injects from CLI
injectKeys.reduce(
(dict, key) => {
dict[key] = cliArgs[key];
return dict;
},
cliBuildInjects as any
);
// Get dist info
const distFolder = cliArgs.dist;
const indexHtml = fs.readFileSync(path.resolve(distFolder, 'index.html'), 'utf8');
const indexHtmlWithInjection = overwriteBuildInjects(indexHtml, cliBuildInjects);
// Basic server config
const app = express();
app.set('host', cliArgs.host);
app.set('port', cliArgs.port);
// Distribute build on all routes
app.use(express.static(distFolder, {index: false}));
app.use('/', index);
// Start server
app.listen(app.get('port'), app.get('host'), () => {
console.log(`BuildInjects`, JSON.stringify(cliBuildInjects, null, 2));
console.log(`DistServer is running at http://${app.get('host')}:${app.get('port')}`);
});
function index (req: express.Request, res: express.Response) {
res.send(indexHtmlWithInjection);
}
/**
* Our webpack builds contain an index.html that already has all scripts and assets linked, including the BuildInjects.
* However, when we serve the build we want to override the BuildInjects that were applied at build time.
*/
function overwriteBuildInjects (html: string, injects: BuildInjects) {
return html.replace(/<script.*?class="buildInjects".*?>.*?<\/script>/, `
<script type="text/javascript">
window.buildInjects = ${JSON.stringify(injects)};
</script>
`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment