-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
babel-transform-compiler-flags.ts
52 lines (46 loc) · 1.29 KB
/
babel-transform-compiler-flags.ts
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
import type { NodePath, PluginObj, types, PluginPass } from "@babel/core"
interface IPluginOptions {
flags: Record<string, string>
availableFlags: Array<string>
}
export default function compilerFlags(
{
types: t,
}: {
types: typeof types
},
opts: Partial<IPluginOptions>
): PluginObj {
if (!opts.flags) {
throw new Error(`flags option needs to be set`)
}
if (!opts.availableFlags) {
throw new Error(`availableFlags option needs to be set`)
}
return {
name: `babel-transform-compiler-flags`,
visitor: {
Identifier(
nodePath: NodePath<types.Identifier>,
state: PluginPass
): void {
const flags = (state.opts as IPluginOptions).flags
const availableFlags = (state.opts as IPluginOptions).availableFlags
if (
nodePath.node.name === `_CFLAGS_` &&
t.isMemberExpression(nodePath.parent)
) {
const cFlag = (nodePath.parent.property as types.Identifier).name
if (!availableFlags.includes(cFlag)) {
throw new Error(
`${cFlag} is not part of the available compiler flags.`
)
}
nodePath.parentPath.replaceWith(
t.stringLiteral(flags[cFlag] ? flags[cFlag] : ``)
)
}
},
},
}
}