This repository has been archived by the owner on Jun 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacro.cjs
51 lines (45 loc) · 1.48 KB
/
macro.cjs
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
let { createMacro, MacroError } = require("babel-plugin-macros")
let pkg = require("./package.json")
module.exports = createMacro(
function invariant({ references, state, babel: { types: t } }) {
let tIdentifier = t.identifier("invariant")
state.file.path.node.body.unshift(
t.importDeclaration(
[t.importDefaultSpecifier(tIdentifier)],
t.stringLiteral(pkg.name + "/invariant"),
),
)
references.default.forEach((refPath) => {
let isProduction = process.env.NODE_ENV === "production"
let parent = refPath.parentPath.node
if (!t.isCallExpression(parent)) {
throw new MacroError(`Expected call expression. Found: ${parent.type}`)
}
if (parent.arguments.length === 0) {
throw new MacroError(
`Unexpected argument count: ${parent.arguments.length}`,
)
}
if (
parent.arguments.length > 2 &&
t.isObjectExpression(parent.arguments[2]) &&
parent.arguments[2].properties.find((x) =>
t.isObjectProperty(x, { key: "env" }),
)?.value.value !== process.env.NODE_ENV
) {
// remove invariant call, if options.env is different from NODE_ENV
refPath.parentPath.remove()
} else {
refPath.parentPath.replaceWith(
t.callExpression(
tIdentifier,
isProduction ? parent.arguments.slice(0, 1) : parent.arguments,
),
)
}
})
},
{
configName: "invariant",
},
)