forked from preactjs/preact
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcodemod-strip-tdz.js
56 lines (46 loc) · 1.33 KB
/
codemod-strip-tdz.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
/* eslint no-console:0 */
// parent node types that we don't want to remove pointless initializations from (because it breaks hoisting)
const BLOCKED = ['ForStatement', 'WhileStatement']; // 'IfStatement', 'SwitchStatement'
/** Removes var initialization to `void 0`, which Babel adds for TDZ strictness. */
export default (file, api) => {
let { jscodeshift } = api,
found = 0;
let code = jscodeshift(file.source)
.find(jscodeshift.VariableDeclaration)
.forEach(handleDeclaration);
function handleDeclaration(decl) {
let p = decl,
remove = true;
while ((p = p.parentPath)) {
if (~BLOCKED.indexOf(p.value.type)) {
remove = false;
break;
}
}
decl.value.declarations.filter(isPointless).forEach( node => {
if (remove===false) {
console.log(`> Skipping removal of undefined init for "${node.id.name}": within ${p.value.type}`);
}
else {
removeNodeInitialization(node);
}
});
}
function removeNodeInitialization(node) {
node.init = null;
found++;
}
function isPointless(node) {
let { init } = node;
if (init) {
if (init.type==='UnaryExpression' && init.operator==='void' && init.argument.value==0) {
return true;
}
if (init.type==='Identifier' && init.name==='undefined') {
return true;
}
}
return false;
}
return found ? code.toSource({ quote: 'single' }) : null;
};