Debian Codegraph @

packages/babel-helper-module-transforms/src/rewrite-this.ts

raw
1 import environmentVisitor from "@babel/helper-environment-visitor";
2 import traverse from "@babel/traverse";
3 import { numericLiteral, unaryExpression } from "@babel/types";
4
5 import type { NodePath, Visitor } from "@babel/traverse";
6
7 /**
8 * A visitor to walk the tree, rewriting all `this` references in the top-level scope to be
9 * `void 0` (undefined).
10 */
11 const rewriteThisVisitor: Visitor = traverse.visitors.merge([
12 environmentVisitor,
13 {
14 ThisExpression(path) {
15 path.replaceWith(unaryExpression("void", numericLiteral(0), true));
16 },
17 },
18 ]);
19
20 export default function rewriteThis(programPath: NodePath) {
21 // Rewrite "this" to be "undefined".
22 traverse(programPath.node, { ...rewriteThisVisitor, noScope: true });
23 }