-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (89 loc) · 2.68 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
const { parse } = require('@babel/parser');
const { getOptions } = require('loader-utils');
const validationOptions = require('schema-utils');
const schema = {
'type': 'object',
'properties': {
'cache': {
'type': 'boolean'
}
}
};
/**
* Parse source code and generate hot module code
*
* @param {string} source
*
* @returns {void}
*/
module.exports = function(source) {
const callback = this.async();
const options = Object.assign({
cache: true,
}, getOptions(this));
validationOptions(schema, options, {name: 'Engine Digital HMR Loader'});
this.cacheable(!!options.cache);
if (process.env.NODE_ENV === 'production' || !this.hot) {
callback(null, source);
return;
}
const body = parse(source, { sourceType: 'unambiguous' }).program.body;
if (body.length > 0) {
const importPaths = body
.filter(({ type }) => type === 'ImportDeclaration')
.map(({ source }) => source.value)
.map(val => `'${val}'`);
const tmpSource = `${source}
/* hot reload */
const walk = function walk(root, call) {
call(root);
if (root.shadowRoot) {
walk(root.shadowRoot, call);
}
Array.from(root.children).forEach((child) => {
walk(child, call);
});
}
const hmr = function hmr() {
if (!module.hot) {
return;
}
module.hot.accept([${importPaths.join(', ')}], function (deps, ...args) {
const comp = __webpack_require__(deps[0]);
let Ctor = comp.default;
if (typeof Ctor === 'undefined' || typeof Ctor.is === 'undefined') {
if (module !== void 0 && module.__proto__ !== void 0 && module.__proto__.exports !== void 0 && module.__proto__.exports.default !== void 0)
Ctor = module.__proto__.exports.default;
}
if (typeof Ctor === 'undefined' || typeof Ctor.is === 'undefined') {
module.hot.decline([${importPaths.join(', ')}]);
return;
}
walk(document.body, async (node) => {
if (node.localName === Ctor.is) {
Ctor.observedAttributes;
const descriptorsS = Object.getOwnPropertyDescriptors(Ctor);
const descriptorsI = Object.getOwnPropertyDescriptors(Ctor.prototype);
for (const name in descriptorsS) {
if (name !== 'length' && name !== 'name' && name !== 'prototype') {
Object.defineProperty(node.constructor, name, descriptorsS[name]);
}
}
for (const name in descriptorsI) {
Object.defineProperty(node, name, descriptorsI[name]);
}
if (node.connectedCallback) {
node.connectedCallback();
node.shouldUpdate(Ctor._classProperties);
node.requestUpdate();
}
}
});
});
}
hmr();
`;
source = tmpSource;
}
callback(null, source);
};