-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathindex.js
82 lines (73 loc) · 2.22 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
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
/**
* @todo change these to their new locations (`prettier/plugins/<parser>`) with
* the next major release. (requires dropping Prettier 2.x support)
*/
// @ts-expect-error
const { parsers: babelParsers } = require('prettier/parser-babel');
// @ts-expect-error
const { parsers: htmlParsers } = require('prettier/parser-html');
// @ts-expect-error
const { parsers: typescriptParsers } = require('prettier/parser-typescript');
const { organize } = require('./lib/organize');
/**
* 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;
}
const isRange =
Boolean(options.originalText) ||
options.rangeStart !== 0 ||
(options.rangeEnd !== Infinity && options.rangeEnd !== code.length);
if (isRange) {
return code; // processing a range doesn't make sense
}
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),
};
};
/**
* @type {import('prettier').Plugin}
*/
const plugin = {
options: {
organizeImportsSkipDestructiveCodeActions: {
type: 'boolean',
default: false,
category: 'OrganizeImports',
description: 'Skip destructive code actions like removing unused imports.',
},
},
parsers: {
babel: withOrganizeImportsPreprocess(babelParsers.babel),
'babel-ts': withOrganizeImportsPreprocess(babelParsers['babel-ts']),
typescript: withOrganizeImportsPreprocess(typescriptParsers.typescript),
vue: withOrganizeImportsPreprocess(htmlParsers.vue),
},
};
module.exports = plugin;