/
injectify.js
43 lines (36 loc) 路 1.28 KB
/
injectify.js
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
import { transform, traverse, types as t, transformFromAst } from 'babel-core';
import wrapperTemplate from './wrapper_template.js';
function processRequireCall(path) {
const dependencyString = path.node.arguments[0].value;
path.replaceWith(t.logicalExpression('||',
t.CallExpression(t.identifier('__getInjection'), [t.stringLiteral(dependencyString)]),
path.node),
);
return dependencyString;
}
export default function injectify(context, source) {
const { ast } = transform(source);
const dependencies = [];
traverse(ast, {
CallExpression(path) {
if (t.isIdentifier(path.node.callee, { name: 'require' })) {
dependencies.push(processRequireCall(path));
path.skip();
}
},
});
if (dependencies.length === 0) {
context.emitWarning('The module you are trying to inject into doesn\'t have any dependencies. ' +
'Are you sure you want to do this?');
}
const dependenciesArrayAst = t.arrayExpression(
dependencies.map(dependency => t.stringLiteral(dependency)),
);
const wrapperModuleAst = t.file(t.program([
wrapperTemplate({ SOURCE: ast, DEPENDENCIES: dependenciesArrayAst }),
]));
return transformFromAst(wrapperModuleAst, source, {
sourceMaps: context.sourceMap,
sourceFileName: context.resourcePath,
});
}