This repository was archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmacro.js
More file actions
65 lines (56 loc) · 1.53 KB
/
macro.js
File metadata and controls
65 lines (56 loc) · 1.53 KB
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
/* eslint-disable no-undef */
const { createMacro } = require('babel-plugin-macros');
const babelPlugin = require('effector/babel-plugin');
module.exports = createMacro(root, {
configName: 'effectorRoot',
});
function root({
references,
state,
babel,
config: { importModuleName = 'effector-root', ...config } = {},
}) {
const program = state.file.path;
// First of all replace import path to effector-root instead of /macro
Object.keys(references).forEach((referenceName) => {
const newName = addImport(
babel.types,
program,
referenceName,
importModuleName,
);
// Change name of method to updated
references[referenceName].forEach((referencePath) => {
referencePath.node.name = newName;
});
});
const instance = babelPlugin(babel, config);
instance.pre();
babel.traverse(program.parent, instance.visitor, undefined, {
...state,
...instance,
});
instance.post();
}
function addImport(t, programPath, specifierName, importPath) {
const [newPath] = programPath.unshiftContainer(
'body',
t.importDeclaration(
[
t.importSpecifier(
programPath.scope.generateUidIdentifier(specifierName),
t.identifier(specifierName),
),
],
t.stringLiteral(importPath),
),
);
let found;
newPath.get('specifiers').forEach((specifier) => {
if (specifier.node.imported.name === specifierName) {
found = specifier;
}
});
programPath.scope.registerBinding('module', found);
return found.node.local.name;
}