-
Notifications
You must be signed in to change notification settings - Fork 5
/
babel.transform.cjs
43 lines (40 loc) · 1.18 KB
/
babel.transform.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
/* eslint-disable @typescript-eslint/no-var-requires */
const { types } = require('@babel/core');
const syntaxTypeScript = require('@babel/plugin-syntax-typescript').default;
/**
* Plugin to transpile all enums into const object for inlining.
* Inspired by babel-plugin-const-enum plugin.
*
* @type {() => import('@babel/core').PluginObj}
*/
module.exports = function enumToConstObject() {
return {
name: 'enum-to-const-object',
inherits: syntaxTypeScript,
visitor: {
TSEnumDeclaration(path) {
const [constObjectPath] = path.replaceWith(
tsEnumDeclarationToConstObject(path)
);
path.scope.registerDeclaration(constObjectPath);
},
},
};
};
function tsEnumDeclarationToConstObject(path) {
return types.variableDeclaration('const', [
types.variableDeclarator(
path.node.id,
types.objectExpression(
tsEnumMembersToObjectProperties(path.get('members')),
),
),
]);
}
function tsEnumMembersToObjectProperties(memberPaths) {
return memberPaths.map((path) => {
const keyNode = path.node.id;
const valueNode = path.node.initializer;
return types.objectProperty(keyNode, valueNode);
});
}