/
load-ts-transformers.ts
86 lines (76 loc) · 2.17 KB
/
load-ts-transformers.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { logger } from '@nrwl/devkit';
import { join } from 'path';
import {
CompilerPlugin,
CompilerPluginHooks,
TransformerEntry,
TransformerPlugin,
} from './types';
export function loadTsTransformers(
plugins: TransformerEntry[],
moduleResolver: typeof require.resolve = require.resolve
): {
compilerPluginHooks: CompilerPluginHooks;
hasPlugin: boolean;
} {
const beforeHooks: CompilerPluginHooks['beforeHooks'] = [];
const afterHooks: CompilerPluginHooks['afterHooks'] = [];
const afterDeclarationsHooks: CompilerPluginHooks['afterDeclarationsHooks'] =
[];
if (!plugins || !plugins.length)
return {
compilerPluginHooks: {
beforeHooks,
afterHooks,
afterDeclarationsHooks,
},
hasPlugin: false,
};
const normalizedPlugins: TransformerPlugin[] = plugins.map((plugin) =>
typeof plugin === 'string' ? { name: plugin, options: {} } : plugin
);
const nodeModulePaths = [
join(process.cwd(), 'node_modules'),
...module.paths,
];
const pluginRefs: CompilerPlugin[] = normalizedPlugins.map(({ name }) => {
try {
const binaryPath = moduleResolver(name, {
paths: nodeModulePaths,
});
return require(binaryPath);
} catch (e) {
logger.warn(`"${name}" plugin could not be found!`);
return {};
}
});
for (let i = 0; i < pluginRefs.length; i++) {
const { name: pluginName, options: pluginOptions } = normalizedPlugins[i];
const { before, after, afterDeclarations } = pluginRefs[i];
if (!before && !after && !afterDeclarations) {
logger.warn(
`${pluginName} is not a Transformer Plugin. It does not provide neither before(), after(), nor afterDeclarations()`
);
continue;
}
if (before) {
beforeHooks.push(before.bind(before, pluginOptions));
}
if (after) {
afterHooks.push(after.bind(after, pluginOptions));
}
if (afterDeclarations) {
afterDeclarationsHooks.push(
afterDeclarations.bind(afterDeclarations, pluginOptions)
);
}
}
return {
compilerPluginHooks: {
beforeHooks,
afterHooks,
afterDeclarationsHooks,
},
hasPlugin: true,
};
}