import * as express from 'express' import * as path from 'path' import { readIndexHtml } from './readIndexHtml' const environment = process.env.NODE_ENV || 'development' export interface IServePublicOptions { injectClientConfiguration?: any injectPostHeadStart?: string injectPreHeadEnd?: string injectPostBodyStart?: string injectPreBodyEnd?: string webpackConfig?: any } export function servePublic(publicPath: string, options?: IServePublicOptions): express.Handler { if (environment === 'production') { const assetsMiddleware = express.static(path.resolve(publicPath)) const htmlPromise = readIndexHtml(publicPath) return async (req, res, next) => { if (req.method === 'GET' && req.path.match(/^\/assets\//)) { assetsMiddleware(req, res, next) } else if (req.method === 'GET' && req.accepts('html')) { const html = augmentHtml(await htmlPromise, options) res.writeHead(200, { 'content-type': 'text/html' }) res.write(html) res.end() } else { next() } } } else { const webpack = require('webpack') const webpackConfig = (options && options.webpackConfig) || require('./webpack.config.js') const webpackCompiler = webpack(webpackConfig) const webpackDevMiddlware = require('webpack-dev-middleware')(webpackCompiler) return (req, res, next) => { if (req.method === 'GET' && req.path.match(/^\/assets\//)) { webpackDevMiddlware(req, res, next) } else if (req.method === 'GET' && req.accepts('html')) { const originalSend = res.send req.url = '/' // tslint:disable-next-line only-arrow-functions res.send = function(content) { const transformedContent = Buffer.from(augmentHtml(content.toString('utf8'), options)) return originalSend.call(this, transformedContent) } webpackDevMiddlware(req, res, next) } else { next() } } } } function augmentHtml(html: string, options?: IServePublicOptions): string { let result = html if (options && options.injectClientConfiguration) { result = result.replace( '', `` ) } if (options && options.injectPostHeadStart) { result = result.replace('', `${options.injectPostHeadStart}`) } if (options && options.injectPreHeadEnd) { result = result.replace('', `${options.injectPreHeadEnd}`) } if (options && options.injectPostBodyStart) { result = result.replace('', `${options.injectPostBodyStart}`) } if (options && options.injectPreBodyEnd) { result = result.replace('', `${options.injectPreBodyEnd}`) } return result }