-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
68 lines (51 loc) · 1.97 KB
/
index.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
'use strict';
const sysPath = require('path');
const swPrecache = require('sw-precache');
const cheerio = require('cheerio');
const defaultSWOptions = {staticFileGlobs: []};
class SWCompiler {
constructor(config) {
this._setConfig(config);
}
_setConfig(cfg) {
const publicPath = cfg.paths.public;
const config = cfg.plugins.swPrecache || {};
this.swFileName = config.swFileName || 'sw.js';
this.swFilePath = sysPath.join(publicPath, this.swFileName);
this.autorequire = Array.isArray(config.autorequire) || config.autorequire === true ? config.autorequire : false;
this.options = config.options || defaultSWOptions;
if (!this.options.staticFileGlobs.length) this.options.staticFileGlobs.push(`${publicPath}/**/*.*`);
}
_changeFileContent(fileContent) {
/* eslint-disable no-useless-escape */
// if file service worker was included into file
if (fileContent.indexOf(this.swFileName) >= 0) return fileContent;
const $ = cheerio.load(fileContent);
const swSource = `\<script src='${this.swFileName}'\>\<\/script\>\n`;
const registrationScript = `\<script\>if ('serviceWorker' in navigator) navigator.serviceWorker.register('${this.swFileName}')\<\/script\>\n`;
$('html').append(swSource, registrationScript);
return $.html();
}
onCompile() {
return swPrecache.write(this.swFilePath, this.options);
}
compileStatic(file) {
const data = file.data;
const path = file.path;
if (this.autorequire === true || path.indexOf(this.autorequire) >= 0) {
try {
const source = this._changeFileContent(data);
return Promise.resolve(source);
} catch (error) {
return Promise.reject(error);
}
}
return Promise.resolve(data);
}
}
// Required for all Brunch plugins.
SWCompiler.prototype.brunchPlugin = true;
SWCompiler.prototype.type = 'template';
SWCompiler.prototype.extension = 'html';
SWCompiler.prototype.staticTargetExtension = 'html';
module.exports = SWCompiler;