-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
54 lines (48 loc) · 1.91 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
const path = require('path');
function hmr(source) {
const context = this;
this.cacheable();
let entryFile = [];
const entry = this.options.entry;
const customEntrypoint = this.options.entryPoint;
if (customEntrypoint) {
const isValid = Object.prototype.toString.call(customEntrypoint) === ['object String'];
if (!isValid) {
throw new Error('The entryPoint should be a valid string');
}
entryFile = customEntrypoint;
} else {
const entryType = Object.prototype.toString.call(entry);
if (entryType === '[object Array]') {
// Falling back to the last item in the entry array
entryFile = entry[entry.length - 1];
} else if (entryType === '[object Object]') {
// Named entries.
// There could be multiple named entries. So iterating that.
Object.keys(entry).forEach((namedEntry) => {
const namedEntryType = Object.prototype.toString.call(entry[namedEntry]);
// Now this named entry either can be a single string or a string array
if (namedEntryType === '[object String]') {
entryFile.push(entry[namedEntry]);
} else if (namedEntryType === '[object Array]') {
// We take the last item from the named array entry
entryFile.push(entry[namedEntry][entry[namedEntry].length - 1]);
}
});
}
}
let isQualified;
const contextBase = context.context;
if (Object.prototype.toString.call(entryFile) === '[object String]') {
const basePath = path.resolve(contextBase, path.basename(entryFile));
isQualified = basePath === context.resourcePath;
} else if (Object.prototype.toString.call(entryFile) === '[object Array]') {
isQualified = entryFile
.some(item => context.resourcePath === path.resolve(contextBase, path.basename(item)));
}
if (isQualified) {
return `${source}\r\n\r\nif (module.hot) {\r\nmodule.hot.accept();\r\n}\r\n`;
}
return source;
}
module.exports = hmr;