/
index.js
79 lines (71 loc) 路 2.01 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
import { declare } from "@babel/helper-plugin-utils";
import annotateAsPure from "@babel/helper-annotate-as-pure";
import { types as t } from "@babel/core";
// Mapping of React top-level methods that are pure.
// This plugin adds a /*#__PURE__#/ annotation to calls to these methods,
// so that terser and other minifiers can safely remove them during dead
// code elimination.
// See https://reactjs.org/docs/react-api.html
const PURE_CALLS = new Map([
[
"react",
[
"cloneElement",
"createElement",
"createFactory",
"createRef",
"forwardRef",
"isValidElement",
"memo",
"lazy",
],
],
["react-dom", ["createPortal"]],
]);
export default declare(api => {
api.assertVersion(7);
return {
name: "transform-react-pure-annotations",
visitor: {
CallExpression(path) {
if (isReactCall(path)) {
annotateAsPure(path);
}
},
},
};
});
function isReactCall(path) {
// If the callee is not a member expression, then check if it matches
// a named import, e.g. `import {forwardRef} from 'react'`.
if (!t.isMemberExpression(path.node.callee)) {
const callee = path.get("callee");
for (const [module, methods] of PURE_CALLS) {
for (const method of methods) {
if (callee.referencesImport(module, method)) {
return true;
}
}
}
return false;
}
// Otherwise, check if the member expression's object matches
// a default import (`import React from 'react'`) or namespace
// import (`import * as React from 'react'), and check if the
// property matches one of the pure methods.
for (const [module, methods] of PURE_CALLS) {
const object = path.get("callee.object");
if (
object.referencesImport(module, "default") ||
object.referencesImport(module, "*")
) {
for (const method of methods) {
if (t.isIdentifier(path.node.callee.property, { name: method })) {
return true;
}
}
return false;
}
}
return false;
}