-
Notifications
You must be signed in to change notification settings - Fork 48
/
import-meta-env.ts
48 lines (40 loc) · 1.35 KB
/
import-meta-env.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
/**
* Forked from https://github.com/iendeavor/import-meta-env/tree/main/packages/babel 0.4.2 (MIT License - Copyright (c) 2021 Ernest)
*/
import type { PluginObj } from "@babel/core";
import type { Identifier, MemberExpression, MetaProperty } from "@babel/types";
export function importMetaEnvPlugin({ template, types }: any) {
return <PluginObj>{
name: "@import-meta-env/babel",
visitor: {
Identifier(path) {
if (!types.isIdentifier(path)) {
return;
}
// {}.{} or {}?.{} (meta.env or meta?.env)
if (
!types.isMemberExpression(path.parentPath) &&
!types.isOptionalMemberExpression(path.parentPath)
) {
return;
}
// {}.{}.{} (import.meta.env)
if (!types.isMemberExpression(path.parentPath.node)) {
return;
}
const parentNode = path.parentPath.node as MemberExpression;
if (!types.isMetaProperty(parentNode.object)) {
return;
}
const parentNodeObjMeta = parentNode.object as MetaProperty;
if (
parentNodeObjMeta.meta.name === "import" &&
parentNodeObjMeta.property.name === "meta" &&
(parentNode.property as Identifier).name === "env"
) {
path.parentPath.replaceWith(template.expression.ast("process.env"));
}
},
},
};
}