-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule-resolver.js
78 lines (65 loc) · 1.81 KB
/
module-resolver.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
self.addEventListener('fetch', function(event) {
event.respondWith(
Promise.resolve().then(()=>{
let url = event.request.url.replace(location.origin, '').replace(/^\//, '');
if(url.split('?')[0] === '' || url.indexOf('src/') === -1) {
return fetch(event.request);
}
url = resolveUrl(url);
url = `${location.origin}/${url}`;
const request = copyRequest(event.request, {url});
return fetch(request).then(rewrite);
})
);
});
function rewrite(response) {
const matched = response.url.match(/\.(\w+)(\?|$)/);
if(!matched) {
return response;
}
const type = matched[1];
if(type === 'html' || type === 'css') {
return response.text().then((text)=>{
const wrappedText = `export default \`${text}\``;
return copyResponse(response, {
body: wrappedText,
headers:{
"content-type": "application/javascript"
}});
});
}
return response;
}
const roots = {
jquery: 'node_modules/jquery/dist/jquery.js'
};
function resolveUrl(url) {
const prefix = url.split('/');
const root = roots[prefix[0]];
if(root) {
prefix.splice(0, 1, root);
}
return prefix.join('/');
}
function copyResponse(response, {body, headers={}}) {
const defaultHeaders = {};
response.headers.forEach((v,k)=>defaultHeaders[k] = v);
Object.entries(headers).forEach(([k, v])=>defaultHeaders[k] = v);
return new Response(body, {
headers: defaultHeaders,
status: response.status,
statusText: response.statusText
});
}
function copyRequest(request, {url}) {
return new Request(url, {
method: 'GET',
headers: request.headers,
mode: request.mode,
credentials: request.credentials,
cache: request.cache,
redirect: request.redirect,
referrer: request.referrer,
integrity: request.integrity
});
}