2018-02-17 00:00:06 +00:00
|
|
|
const fs = require("fs");
|
|
|
|
const invariant = require("invariant");
|
2018-05-21 20:26:00 +00:00
|
|
|
|
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; " +
|
2018-05-21 20:26:00 +00:00
|
|
|
"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;
|