refactor: serving
This commit is contained in:
parent
a4c02dac7a
commit
2ec9fa3fa9
|
@ -41,7 +41,7 @@ const common = async (latus, req) => {
|
|||
return instance.webpack();
|
||||
};
|
||||
|
||||
const varyBy = (req) => (req.user || 0) && req.user.id;
|
||||
const varyBy = () => 0;
|
||||
|
||||
const vary = (latus, fn) => {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
|
@ -86,38 +86,25 @@ const production = (latus) => vary(
|
|||
};
|
||||
config.output.path = `${config.context}/build/assets`;
|
||||
const compiler = webpack(config);
|
||||
let hasRun = false;
|
||||
return (req, res, next) => {
|
||||
if (hasRun) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
compiler.run((error, stats) => {
|
||||
if (error) {
|
||||
next(error);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
res.setHeader('Content-Type', 'application/javascript; charset=UTF-8');
|
||||
if (stats.hasErrors()) {
|
||||
const renderedStats = stats.toString({
|
||||
reject(new Error(stats.toString({
|
||||
all: false,
|
||||
errors: true,
|
||||
}).replace(new RegExp(process.cwd(), 'g'), '<cwd>');
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(renderedStats);
|
||||
res.send([
|
||||
'window.addEventListener("load", () => {',
|
||||
"window.document.body.innerHTML = '<pre>' + ",
|
||||
`decodeURIComponent("${encodeURIComponent(renderedStats)}")`,
|
||||
" + '</pre>';",
|
||||
'});',
|
||||
].join(''));
|
||||
}).replace(new RegExp(process.cwd(), 'g'), '<cwd>')));
|
||||
}
|
||||
else {
|
||||
hasRun = true;
|
||||
next();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
return (req, res, next) => {
|
||||
promise.then(next).catch(next);
|
||||
};
|
||||
},
|
||||
);
|
||||
|
|
|
@ -74,6 +74,7 @@ export const createHttpServer = async (latus) => {
|
|||
else {
|
||||
app.use(express.static(join(__dirname, 'client')));
|
||||
app.get('*', async (req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
|
||||
const stream = createReadStream(join(__dirname, 'client', 'index.html'));
|
||||
stream.pipe(res);
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue
Block a user