-
Notifications
You must be signed in to change notification settings - Fork 799
/
babel.dev.js
277 lines (240 loc) · 8.44 KB
/
babel.dev.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { REGENERATE_METHOD } from './internal/constants';
import fresh from './fresh/babel';
const templateOptions = {
placeholderPattern: /^([A-Z0-9]+)([A-Z0-9_]+)$/,
};
/* eslint-disable */
const shouldIgnoreFile = file =>
!!file
.split('\\')
.join('/')
.match(/node_modules\/(react|react-dom|react-hot-loader)([\/]|$)/);
/* eslint-enable */
function plugin(args, options = {}) {
// This is a Babel plugin, but the user put it in the Webpack config.
if (this && this.callback) {
throw new Error(
'React Hot Loader: You are erroneously trying to use a Babel plugin ' +
'as a Webpack loader. We recommend that you use Babel, ' +
'remove "react-hot-loader/babel" from the "loaders" section ' +
'of your Webpack configuration, and instead add ' +
'"react-hot-loader/babel" to the "plugins" section of your .babelrc file. ' +
'If you prefer not to use Babel, replace "react-hot-loader/babel" with ' +
'"react-hot-loader/webpack" in the "loaders" section of your Webpack configuration. ',
);
}
const { types: t, template } = args;
const { safetyNet = true } = options;
const buildRegistration = template('reactHotLoader.register(ID, NAME, FILENAME);', templateOptions);
const signatureHeader = template(
`var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {return a;}`,
templateOptions,
);
const headerTemplate = template(
`(function () {
var enterModule = (typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined);
enterModule && enterModule(module);
}())`,
templateOptions,
);
const footerTemplate = template(
`(function () {
var leaveModule = (typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined);
leaveModule && leaveModule(module);
}())`,
templateOptions,
);
const evalTemplate = template('this[key]=eval(code);', templateOptions);
// We're making the IIFE we insert at the end of the file an unused variable
// because it otherwise breaks the output of the babel-node REPL (#359).
const buildTagger = template(
`
(function () {
var reactHotLoader = (typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined);
if (!reactHotLoader) {
return;
}
REGISTRATIONS
}());
`,
templateOptions,
);
// Gather top-level variables, functions, and classes.
// Try our best to avoid variables from require().
// Ideally we only want to find components defined by the user.
function shouldRegisterBinding(binding) {
const { type, node, parent } = binding.path;
switch (type) {
case 'FunctionDeclaration':
case 'ClassDeclaration':
case 'VariableDeclaration':
return true;
case 'VariableDeclarator': {
const { init } = node;
if (t.isCallExpression(init) && init.callee.name === 'require') {
return false;
}
if (parent.declare) {
return false;
}
return true;
}
default:
return false;
}
}
const REGISTRATIONS = Symbol('registrations');
return {
visitor: {
ExportDefaultDeclaration(path, state) {
const { file } = state;
// Default exports with names are going
// to be in scope anyway so no need to bother.
if (path.node.declaration.id) {
return;
}
// Move export default right hand side to a variable
// so we can later refer to it and tag it with __source.
const id = path.scope.generateUidIdentifier('default');
const expression = t.isExpression(path.node.declaration)
? path.node.declaration
: t.toExpression(path.node.declaration);
path.scope.registerDeclaration(
path.insertBefore(t.variableDeclaration('const', [t.variableDeclarator(id, expression)]))[0],
);
path.node.declaration = id; // eslint-disable-line no-param-reassign
// It won't appear in scope.bindings
// so we'll manually remember it exists.
state[REGISTRATIONS].push(
buildRegistration({
ID: id,
NAME: t.stringLiteral('default'),
FILENAME: t.stringLiteral(file.opts.filename),
}),
);
},
Program: {
enter({ scope, node }, state) {
const { file } = state;
state[REGISTRATIONS] = []; // eslint-disable-line no-param-reassign
node.body.unshift(signatureHeader());
// Everything in the top level scope, when reasonable,
// is going to get tagged with __source.
/* eslint-disable guard-for-in,no-restricted-syntax */
for (const id in scope.bindings) {
const binding = scope.bindings[id];
if (shouldRegisterBinding(binding)) {
state[REGISTRATIONS].push(
buildRegistration({
ID: binding.identifier,
NAME: t.stringLiteral(id),
FILENAME: t.stringLiteral(file.opts.filename),
}),
);
}
}
/* eslint-enable */
},
exit({ node }, state) {
const { file } = state;
const registrations = state[REGISTRATIONS];
state[REGISTRATIONS] = [];
// inject the code only if applicable
if (registrations && registrations.length && !shouldIgnoreFile(file.opts.filename)) {
if (safetyNet) {
node.body.unshift(headerTemplate());
}
// Inject the generated tagging code at the very end
// so that it is as minimally intrusive as possible.
node.body.push(t.emptyStatement());
node.body.push(buildTagger({ REGISTRATIONS: registrations }));
node.body.push(t.emptyStatement());
if (safetyNet) {
node.body.push(footerTemplate());
}
}
},
},
Class(classPath) {
const classBody = classPath.get('body');
let hasRegenerateMethod = false;
let hasMethods = false;
classBody.get('body').forEach(path => {
const { node } = path;
// don't apply transform to static class properties
if (node.static) {
return;
}
if (node.key.name !== REGENERATE_METHOD) {
hasMethods = true;
} else {
hasRegenerateMethod = true;
}
});
if (hasMethods && !hasRegenerateMethod) {
const regenerateMethod = t.classMethod(
'method',
t.identifier(REGENERATE_METHOD),
[t.identifier('key'), t.identifier('code')],
t.blockStatement([evalTemplate()]),
);
classBody.pushContainer('body', regenerateMethod);
classBody.get('body').forEach(path => {
const { node } = path;
if (node.key.name === REGENERATE_METHOD) {
path.addComment('leading', ' @ts-ignore', true);
path
.get('body')
.get('body')[0]
.addComment('leading', ' @ts-ignore', true);
}
});
}
},
},
};
}
const mergeRecord = (sourceRecord, newRecord) => {
Object.keys(newRecord).forEach(key => {
const action = newRecord[key];
if (typeof action === 'function') {
if (!sourceRecord[key]) {
sourceRecord[key] = () => ({});
}
const prev = sourceRecord[key];
sourceRecord[key] = (...args) => {
prev(...args);
action(...args);
};
} else if (typeof action === 'object') {
if (!sourceRecord[key]) {
sourceRecord[key] = {};
}
mergeRecord(sourceRecord[key], action);
}
});
};
const composePlugins = plugins => (...args) => {
const result = {};
plugins.forEach(creator => {
const plugin = creator(...args);
mergeRecord(result, plugin);
});
return result;
};
module.exports = composePlugins([
plugin,
(...args) => {
const p = fresh(...args);
// removing everything we dont want right now
// registration
// delete p.visitor.Program;
// delete p.visitor.Program.exit;
// registrations
// delete p.visitor.FunctionDeclaration.enter;
// delete p.visitor.FunctionDeclaration.leave;
// delete p.visitor.VariableDeclaration;
return p;
},
]);
module.exports.shouldIgnoreFile = shouldIgnoreFile;