forked from mlaursen/react-md
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSWOfflinePlugin.js
More file actions
59 lines (53 loc) · 1.54 KB
/
SWOfflinePlugin.js
File metadata and controls
59 lines (53 loc) · 1.54 KB
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
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const { transform } = require('babel-core');
const UglifyJS = require('uglify-js');
const readFile = Promise.promisify(fs.readFile);
/**
* This is a plugin to create and minify the offline service worker importScript
* that is used by the main SWPrecachePlugin.
*/
module.exports = class SWOfflinePlugin {
constructor(options) {
this.options = options;
this.config = {};
}
apply(compiler) {
compiler.plugin('after-emit', (compilation, callback) => {
this.configure(compiler);
this.write(compiler)
.then(() => callback())
.catch(error => callback(error));
});
}
configure(compiler) {
const { cacheId, entry, filename } = this.options;
const { filepath = path.resolve(compiler.outputPath, filename) } = this.options;
this.config = {
cacheId,
entry,
filename,
filepath,
babel: {
babelrc: false,
presets: [
['env', {
targets: {
browsers: ['last 2 versions', 'safari >= 7'],
},
}],
],
},
};
}
write(compiler) {
return readFile(this.config.entry, 'UTF-8')
.then(code => code.replace(/__CACHE_ID__/, this.config.cacheId))
.then(code => transform(code, this.config.babel).code)
.then(code => UglifyJS.minify(code).code)
.then(code => new Promise((resolve) => {
compiler.outputFileSystem.writeFile(this.config.filepath, code, resolve);
}));
}
};