forked from simonhaenisch/prettier-plugin-organize-imports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (47 loc) · 1.58 KB
/
index.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
44
45
46
47
48
49
50
51
52
53
const { parsers: babelParsers } = require('prettier/parser-babel');
const { parsers: htmlParsers } = require('prettier/parser-html');
const { parsers: typescriptParsers } = require('prettier/parser-typescript');
const ts = require('typescript');
const { organize } = require('./lib/organize');
const { applyTextChanges } = require('./lib/apply-text-changes');
/**
* Organize the code's imports using the `organizeImports` feature of the TypeScript language service API.
*
* @param {string} code
* @param {import('prettier').ParserOptions} options
*/
const organizeImports = (code, options) => {
if (code.includes('// organize-imports-ignore') || code.includes('// tslint:disable:ordered-imports')) {
return code;
}
try {
return organize(code, options);
} catch (error) {
if (process.env.DEBUG) {
console.error(error);
}
return code;
}
};
/**
* Set `organizeImports` as the given parser's `preprocess` hook, or merge it with the existing one.
*
* @param {import('prettier').Parser} parser prettier parser
*/
const withOrganizeImportsPreprocess = (parser) => {
return {
...parser,
/**
* @param {string} code
* @param {import('prettier').ParserOptions} options
*/
preprocess: (code, options) =>
organizeImports(parser.preprocess ? parser.preprocess(code, options) : code, options),
};
};
exports.parsers = {
babel: withOrganizeImportsPreprocess(babelParsers.babel),
'babel-ts': withOrganizeImportsPreprocess(babelParsers['babel-ts']),
typescript: withOrganizeImportsPreprocess(typescriptParsers.typescript),
vue: withOrganizeImportsPreprocess(htmlParsers.vue),
};