-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanifest-plugin.js
83 lines (70 loc) · 2.82 KB
/
manifest-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var fs = require("fs");
var fse = require("fs-extra");
const crypto = require("crypto");
var DEFAULT_PARAMS = {
manifestFile: "/rails-app/config/sprockets-manifest.json",
statsFile: "webpack-stats.json"
};
function WebpackSprocketsRailsManifestPlugin(options) {
var params = options || {};
this._manifestFile = params.manifestFile || DEFAULT_PARAMS.manifestFile;
this._statsFile = params.statsFile || DEFAULT_PARAMS.statsFile;
}
function processFile(outputPath, sprockets, logicalPath, chunkFilename) {
var chunkPath = outputPath + "/" + chunkFilename;
var stat = fs.statSync(chunkPath);
const fileBuffer = fs.readFileSync(chunkPath);
const hashSum = crypto.createHash('sha256');
hashSum.update(fileBuffer);
const hash = hashSum.digest('base64');
const hexHash = Buffer.from(hash, 'base64').toString('hex');
sprockets.files[chunkFilename] = {
"logical_path": logicalPath,
"mtime": stat.mtime.toISOString(),
"size": stat.size,
"digest": hexHash,
"integrity": "sha256-" + hash
};
sprockets.assets[logicalPath] = chunkFilename;
}
WebpackSprocketsRailsManifestPlugin.prototype.apply = function(compiler) {
var manifestFile = this._manifestFile;
var statsFile = this._statsFile;
var sprockets = {
files: {},
assets: {}
};
compiler.hooks.done.tap("WebpackSprocketsRailsManifestPlugin", function(stats) {
var statsJson = stats.toJson();
var chunks = statsJson.chunks;
var devServer = compiler.options.devServer;
var outputPath;
if (devServer && devServer.contentBase) {
outputPath = devServer.contentBase;
} else {
outputPath = compiler.options.output.path;
}
var manifestPath = outputPath + "/" + manifestFile;
chunks.forEach(function(chunk) {
const logicalName = chunk.names[0];
chunk.files.forEach(filename => {
const chunkExtension = filename.split(".").pop();
processFile(outputPath, sprockets, `${logicalName}.${chunkExtension}`, filename)
});
chunk.auxiliaryFiles
.filter(name => !name.endsWith('.map'))
.forEach(filename => {
const nameParts = filename.split(".");
processFile(outputPath, sprockets, `${nameParts[0]}.${nameParts[2]}`, filename)
});
});
fse.mkdirpSync(outputPath);
// delete files matching glob pattern
let regex = /\.sprockets-manifest-.*\.json$/
fs.readdirSync(outputPath)
.filter(f => regex.test(f))
.map(f => fs.unlinkSync(outputPath + "/" + f));
fse.outputFileSync(manifestPath, JSON.stringify(sprockets, null, " "));
});
};
module.exports = WebpackSprocketsRailsManifestPlugin;