unpkg/modules/middleware/staticAssets.js

32 lines
744 B
JavaScript
Raw Normal View History

2018-02-17 00:00:06 +00:00
const fs = require("fs");
const invariant = require("invariant");
2018-07-18 07:10:37 +00:00
const createAssets = require("./utils/createAssets");
2018-02-17 00:00:06 +00:00
/**
2018-07-18 07:10:37 +00:00
* An express middleware that sets req.assets from the build
2018-02-17 00:00:06 +00:00
* info in the given stats file. Should be used in production.
*/
function staticAssets(webpackStatsFile) {
let stats;
try {
stats = JSON.parse(fs.readFileSync(webpackStatsFile, "utf8"));
} catch (error) {
invariant(
false,
"staticAssets middleware cannot read the build stats in %s; " +
"run the `build` script before starting the server",
2018-02-17 00:00:06 +00:00
webpackStatsFile
);
}
2018-07-18 07:10:37 +00:00
const assets = createAssets(stats);
2018-02-17 00:00:06 +00:00
return (req, res, next) => {
2018-07-18 07:10:37 +00:00
req.assets = assets;
2018-02-17 00:00:06 +00:00
next();
};
}
module.exports = staticAssets;