-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
82 lines (69 loc) · 2.13 KB
/
index.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
import path from 'path';
import sortImports from 'import-sort';
import { IConfigByGlobs, getConfig } from 'import-sort-config';
import { Plugin } from 'prettier';
import { parsers as javascriptParsers } from 'prettier/parser-babel';
import { parsers as typescriptParsers } from 'prettier/parser-typescript';
import invariant from 'tiny-invariant';
const msg = (message: string) => `prettier-config-monots SORTER: ${message}`;
const DEFAULT_PARSER = 'typescript';
const DEFAULT_STYLE = 'custom';
export const defaultConfig: IConfigByGlobs = {
'.js, .jsx, .es6, .es, .mjs, .ts, .tsx': {
parser: DEFAULT_PARSER,
style: DEFAULT_STYLE,
options: {},
},
};
const getAndCheckConfig = (extension: string, fileDirectory: string) => {
const resolvedConfig = getConfig(extension, fileDirectory, defaultConfig);
invariant(
resolvedConfig,
msg(`No configuration found for file type ${extension}`),
);
const rawParser = resolvedConfig.config.parser;
const rawStyle = resolvedConfig.config.style;
invariant(rawParser, `No parser defined for file type ${extension}`);
invariant(rawStyle, `No style defined for file type ${extension}`);
const { parser, style } = resolvedConfig;
invariant(parser, `Parser "${rawParser}" could not be resolved`);
invariant(
style ?? style === rawStyle,
`Style "${rawStyle}" could not be resolved`,
);
return resolvedConfig;
};
const organizeImports = (unsortedCode: string, extension: string) => {
// this throw exceptions up to prettier
const config = getAndCheckConfig(
extension,
path.resolve(__dirname, '..', '..'),
);
const {
parser = DEFAULT_PARSER,
style = DEFAULT_STYLE,
config: rawConfig,
} = config;
const sortResult = sortImports(
unsortedCode,
parser,
style,
`dummy${extension}`,
rawConfig.options,
);
return sortResult.code;
};
export const parsers: Plugin['parsers'] = {
typescript: {
...typescriptParsers.typescript,
preprocess(text) {
return organizeImports(text, '.ts');
},
},
babel: {
...javascriptParsers.babel,
preprocess(text) {
return organizeImports(text, '.js');
},
},
};