-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpackAssetsListPlugin.js
49 lines (38 loc) · 1.56 KB
/
webpackAssetsListPlugin.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
const path = require("path");
const fs = require("fs");
// see https://webpack.js.org/contribute/writing-a-plugin/
class WebpackAssetsListPlugin {
constructor(options = {}) {
this.options = { ...WebpackAssetsListPlugin.defaultOptions, ...options };
}
static defaultOptions = {
outputFile: "sw.js"
};
static urlsListPattern = `"__SERVICE_WORKER_URLS"`;
static cacheNamePattern = `"__SERVICE_WORKER_CACHE_NAME"`;
apply(compiler) {
const pluginName = WebpackAssetsListPlugin.name;
compiler.hooks.afterEmit.tap(pluginName, (compilation) => {
const content =
Object.keys(compilation.assets)
.filter((filename) => {
return (
!filename.endsWith(this.options.outputFile)
&& !filename.endsWith(this.options.outputFile + ".map")
);
})
.map((filename) => `"/${filename}"`)
.join(",");
const filePath = path.resolve(
this.options.dir,
this.options.outputFile
);
const fileContent = fs.readFileSync(filePath, "utf8");
const changedFileContent = fileContent
.replace(WebpackAssetsListPlugin.urlsListPattern, content)
.replace(WebpackAssetsListPlugin.cacheNamePattern, `"${new Date().valueOf()}"`);
fs.writeFileSync(filePath, changedFileContent);
});
}
}
module.exports = WebpackAssetsListPlugin;