-
Notifications
You must be signed in to change notification settings - Fork 21
/
preprocessor.ts
59 lines (49 loc) · 1.81 KB
/
preprocessor.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
import { parse as babelParser, ParserOptions } from '@babel/parser';
import traverse, { NodePath } from '@babel/traverse';
import { ImportDeclaration, isTSModuleDeclaration } from '@babel/types';
import { PrettierOptions } from '../types';
import { getCodeFromAst } from '../utils/get-code-from-ast';
import { getSortedNodes } from '../utils/get-sorted-nodes';
import { examineAndNormalizePluginOptions } from '../utils/normalize-plugin-options';
export function preprocessor(code: string, options: PrettierOptions): string {
const { plugins, ...remainingOptions } =
examineAndNormalizePluginOptions(options);
const parserOptions: ParserOptions = {
sourceType: 'module',
attachComment: true,
plugins,
};
const ast = babelParser(code, parserOptions);
const directives = ast.program.directives;
const interpreter = ast.program.interpreter;
const allOriginalImportNodes: ImportDeclaration[] = [];
traverse(ast, {
ImportDeclaration(path: NodePath<ImportDeclaration>) {
const tsModuleParent = path.findParent((p) =>
isTSModuleDeclaration(p.node),
);
if (!tsModuleParent) {
allOriginalImportNodes.push(path.node);
}
},
});
// short-circuit if there are no import declarations
if (allOriginalImportNodes.length === 0) {
return code;
}
// short-circuit if importOrder is an empty array (can be used to disable plugin)
if (!remainingOptions.importOrder.length) {
return code;
}
const nodesToOutput = getSortedNodes(
allOriginalImportNodes,
remainingOptions,
);
return getCodeFromAst({
nodesToOutput,
allOriginalImportNodes,
originalCode: code,
directives,
interpreter,
});
}