Skip to content

Commit 1d7f9a1

Browse files
committed
plugin: register assignments
1 parent 101e5e2 commit 1d7f9a1

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

packages/babel-plugin-hot-reload/index.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,29 @@ function isVariableCandidate(declaration) {
6969
);
7070
}
7171

72+
function isAssignmentCandidate(assignment) {
73+
return isIdentifierCandidate(assignment.left) && assignment.operator === '=';
74+
}
75+
76+
function hotRegister(name, content) {
77+
return {
78+
type: 'CallExpression',
79+
callee: {
80+
type: 'MemberExpression',
81+
object: { type: 'Identifier', name: 'window' },
82+
property: { type: 'Identifier', name: '__assign' },
83+
computed: false,
84+
},
85+
arguments: [
86+
{ type: 'Identifier', name: 'module' },
87+
{ type: 'StringLiteral', value: name },
88+
content,
89+
],
90+
};
91+
}
92+
7293
function hotDeclare(path) {
94+
console.log('replacing', path.node.id);
7395
path.replaceWith({
7496
type: 'VariableDeclarator',
7597
id: {
@@ -131,6 +153,29 @@ module.exports = function({ types }) {
131153
},
132154
});
133155
},
156+
ExpressionStatement(path) {
157+
if (path.parent.type !== 'Program') {
158+
// Only traverse top level variable declaration
159+
return;
160+
}
161+
if (this.file.code.includes('no-hot')) {
162+
return;
163+
}
164+
165+
path.traverse({
166+
AssignmentExpression(path) {
167+
if (isAssignmentCandidate(path.node)) {
168+
if (!isHotCall(path.node.right)) {
169+
console.log('replacing', path.node.left.name);
170+
path.node.right = hotRegister(
171+
path.node.left.name,
172+
path.node.right
173+
);
174+
}
175+
}
176+
},
177+
});
178+
},
134179
},
135180
};
136181
};
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
let LazyCC;
2+
LazyCC = 5;
3+
24
let DoubleLazyCC = LazyCC;

packages/babel-plugin-hot-reload/tests/__snapshots__/fixtures.test.js.snap

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@
33
exports[`hot-reload assignment: assignment 1`] = `
44
"
55
let LazyCC;
6+
LazyCC = 5;
7+
68
let DoubleLazyCC = LazyCC;
79
810
↓ ↓ ↓ ↓ ↓ ↓
911
1012
let LazyCC;
13+
LazyCC = window.__assign(module, \\"LazyCC\\", 5);
1114
1215
let DoubleLazyCC = window.__assign(module, \\"DoubleLazyCC\\", LazyCC);
1316
"

0 commit comments

Comments
 (0)