Skip to content

Commit

Permalink
feat(express): expose stats/asset paths using express
Browse files Browse the repository at this point in the history
add res.locals.hops.{stats,assets} to help with SSR
  • Loading branch information
dmbch committed Feb 19, 2018
1 parent 6be493a commit 74c8173
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions packages/express/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ var https = require('https');

var hopsConfig = require('hops-config');

var stats;
function getStatsFromFile() {
if (!stats) {
var statsFilename = path.join(hopsConfig.buildDir, 'stats.json');
if (fs.existsSync(statsFilename)) {
stats = require(statsFilename);
}
}
return stats || {};
}

function defaultCallback(error) {
if (error) {
console.error(error.stack.toString());
Expand Down Expand Up @@ -64,6 +75,7 @@ exports.rewritePath = function rewritePath(req, res, next) {
};

exports.registerMiddleware = function registerMiddleware(app, middleware) {
app.use(exports.assetsMiddleware);
if (
process.env.HOPS_MODE === 'static' &&
Array.isArray(hopsConfig.locations)
Expand All @@ -76,6 +88,32 @@ exports.registerMiddleware = function registerMiddleware(app, middleware) {
}
};

exports.assetsMiddleware = function assetsMiddleware(req, res, next) {
res.locals.hops = {
stats:
res.locals && res.locals.webpackStats
? res.locals.webpackStats.toJson()
: getStatsFromFile(),
};
res.locals.hops.assets = { js: [], css: [] };
['vendor', 'main'].forEach(function(key) {
var asset = res.locals.hops.stats.assetsByChunkName[key];
if (Array.isArray(asset)) {
var js = asset.find(function(item) {
return item.indexOf('.js') === item.length - 3;
});
js && res.locals.hops.assets.js.push('/' + js);
var css = asset.find(function(item) {
return item.indexOf('.css') === item.length - 4;
});
css && res.locals.hops.assets.css.push('/' + css);
} else if (asset) {
res.locals.hops.assets.js.push('/' + asset);
}
});
next();
};

exports.bootstrap = hopsConfig.bootstrapServer || function() {};

exports.teardown = hopsConfig.teardownServer || function() {};

0 comments on commit 74c8173

Please sign in to comment.