-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
264 lines (226 loc) · 7.89 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/**
* @file serviceWorker register no-cache solution
* @author mj(zoumiaojiang@gmail.com)
*/
const fs = require('fs');
const path = require('path');
const babel = require('@babel/core');
let cwd = process.cwd();
/**
* 对于小于 100 的数字向左补全0
*
* @param {number} value 数字
* @return {string} 补全后的字符串
*/
function padding(value) {
return value < 10 ? `0${value}` : value;
}
/**
* 获取时间戳版本号
*
* @return {string} 版本号
*/
function getVersion() {
let d = new Date();
return ''
+ d.getFullYear()
+ padding(d.getMonth() + 1)
+ padding(d.getDate())
+ padding(d.getHours())
+ padding(d.getMinutes())
+ padding(d.getSeconds());
}
/**
* babel 编译
*
* @param {string} source 源代码
* @return {string} 编译后的代码
*/
function babelCompiler(source) {
return babel.transform(source, {
comments: false,
minified: true,
presets: [
[
'@babel/preset-env',
{
targets: {
node: 3
},
modules: false
}
]
]
}).code;
}
/**
* 判断是否符合指定的规则
*
* @param {string} asset 捕获的文件名
* @param {Array} rules 规则列表
* @return {boolean} 判断的结果
*/
function isIn(asset, rules) {
for (let i = 0, len = rules.length; i < len; i++) {
let rule = rules[i];
if (typeof rule === 'function' && rule.call(this, asset)) {
return true;
}
else if (typeof rule === 'object' && rule instanceof RegExp && rule.test(asset)) {
return true;
}
else if (typeof rule === 'string' && asset.endsWith(rule)) {
return true;
}
}
return false;
}
/**
* 渲染 sw-register.js 的注入入口代码
*
* @param {Object} data 渲染需要提供的数据
* @return {string} 渲染后的内容
*/
function renderSwRegisterEntry(data) {
return '<script>'
+ 'window.onload = function () {'
+ 'var script = document.createElement("script");'
+ 'var firstScript = document.getElementsByTagName("script")[0];'
+ 'script.type = "text/javascript";'
+ 'script.async = true;'
+ 'script.src = "' + data.publicPath + data.fileName + '?v=" + Date.now();'
+ 'firstScript.parentNode.insertBefore(script, firstScript);'
+ '};'
+ '</script>';
}
/* eslint-disable fecs-prefer-class */
/**
* sw Register 插件
*
* @constructor
* @param {Object} options 参数
*/
function SwRegisterPlugin(options = {}) {
let filePath = path.resolve(cwd, (options.filePath || './src/sw-register.js'));
if (!fs.existsSync(filePath)) {
filePath = path.resolve(__dirname, 'templates', 'sw-register.js');
}
this.filePath = filePath;
this.fileName = options.output || path.basename(filePath);
this.version = options.version || getVersion();
this.prefix = options.prefix;
this.excludes = options.excludes || [];
this.includes = options.includes || [];
this.scope = options.scope || '/';
this.entries = options.entries || [];
this.entriesInfo = {};
}
/* eslint-enable fecs-prefer-class */
SwRegisterPlugin.prototype.apply = function (compiler) {
let me = this;
let swRegisterFilePath = me.filePath;
let emitCallback = (compilation, callback) => {
let prefix = me.prefix || compilation.outputOptions.publicPath || '';
if (!/\/$/.test(prefix)) {
prefix += '/';
}
let publicPath = me.publicPath = prefix;
let con = fs.readFileSync(swRegisterFilePath, 'utf-8');
let version = me.version;
/* eslint-disable max-nested-callbacks */
con = babelCompiler(con).replace(/(['"])([^\s;,()]+?\.js[^'"]*)\1/g, item => {
let swFilePath = RegExp.$2;
if (/\.js/g.test(item)) {
item = item.replace(/\?/g, '&');
}
// if is full url path or relative path
if (/^(http(s)?:)?\/\//.test(swFilePath) || swFilePath[0] !== '/') {
return item.replace(/\.js/g, ext => `${ext}?v=${version}`);
}
// if is absolute path
if (swFilePath.indexOf(publicPath) !== 0) {
let ret = item.replace(
swFilePath,
(publicPath + '/' + swFilePath)
.replace(/\/{1,}/g, '/')
.replace(/\.js/g, ext => `${ext}?v=${version}`)
);
return ret;
}
return item.replace(/\.js/g, ext => `${ext}?v=${version}`);
});
if (me.entries.length === 0) {
if (me.scope !== '/') {
con = con.replace(/\.register\(([^\)]+)\)/, `.register($1, {scope: '${me.scope}'})`);
}
compilation.assets[me.fileName] = {
source() {
return con;
},
size() {
return con.length;
}
};
}
else {
me.entries.forEach(entryConfig => {
let entryName = entryConfig.name;
let swName = entryConfig.serviceWorker.swName || `/${entryName}/service-worker.js`;
let swRegisterName = entryConfig.serviceWorker.swRegisterName || `${entryName}/${me.fileName}`;
let scope = entryConfig.serviceWorker.scope;
if (!scope) {
scope = entryConfig.urlReg.toString() === '/^\\//' ? '/' : `/${entryName}/`;
}
me.entriesInfo[entryName] = {swName, swRegisterName, scope};
// add scope to register
let entryContent = con.replace(/\.register\(([^\)]+)\)/, `.register($1, {scope: '${scope}'})`)
.replace('/service-worker.js', '/' + swName);
compilation.assets[`${entryName}/${me.fileName}`] = {
source() {
return entryContent;
},
size() {
return entryContent.length;
}
};
});
}
Object.keys(compilation.assets).forEach(asset => {
// 默认会给每个 html 文件添加 sw-register.js
// 如果指定了不用添加 sw-register.js 的话,可以在 excludes 参数中指定
// 接受三种形式的值:字符串,正则表达式,回调函数
if (!isIn(asset, me.excludes) && (/\.html$/.test(asset) || isIn(asset, me.includes))) {
let htmlContent = compilation.assets[asset].source().toString();
let swRegisterEntryFileContent;
if (me.entries.length !== 0) {
let entryName = asset.match(/(.+?)\/(.+?)\.html$/)[1];
let entryInfo = me.entriesInfo[entryName];
swRegisterEntryFileContent = renderSwRegisterEntry({
publicPath: me.publicPath,
fileName: entryInfo.swRegisterName
});
}
else {
swRegisterEntryFileContent = renderSwRegisterEntry(me);
}
htmlContent = htmlContent.replace(/<\/body>/, `${swRegisterEntryFileContent}</body>`);
compilation.assets[asset] = {
source() {
return htmlContent;
},
size() {
return htmlContent.length;
}
};
}
});
callback && callback();
};
if (compiler.hooks) {
compiler.hooks.emit.tap('emit', emitCallback);
}
else {
compiler.plugin('emit', emitCallback);
}
};
module.exports = SwRegisterPlugin;