-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
85 lines (70 loc) · 1.74 KB
/
main.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
/**
* @file 主入口
* @author [email protected] (wangyisheng)
*/
'use strict';
import sw from './lib/sw-base';
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
// import product/*
const product = requireAll(require.context('./product', true, /^\.\/.*\.js$/));
/**
* 获取缓存名称
*
* @param {Object} config 配置对象
* @return {string} 缓存名称
*/
function getCacheName(config) {
return `@crater-${config.name}@`;
}
/**
* 添加缓存路由规则
*
* @param {Object} config 配置对象
*/
function addRoute(config) {
let cacheName = getCacheName(config);
let {referrerPattern, options} = config;
if (typeof referrerPattern !== 'object') {
return;
}
if (!options) {
options = {
cache: {
name: cacheName
}
};
}
else if (!options.cache) {
options.cache = {
name: cacheName
};
}
else {
options.cache.name = cacheName;
}
// 遍历config的routers,逐条添加到系统中
config.routers.forEach(router => {
let {method = 'all', urlPattern, strategy} = router;
if (typeof urlPattern !== 'object' && typeof urlPattern !== 'function') {
return;
}
sw.add(referrerPattern, method, urlPattern, strategy, options);
});
}
/**
* 添加预缓存文件
*
* @param {Object} config 配置文件
*/
function addPrecache(config) {
let cacheName = getCacheName(config);
sw.precache(cacheName, config.precache);
}
// 加载全部配置,每个都添加路由规则和预缓存
Object.keys(product).forEach(name => {
let config = product[name];
addPrecache(config);
addRoute(config);
});