-
Notifications
You must be signed in to change notification settings - Fork 14
/
.prettier.plugin.js
75 lines (70 loc) · 2.01 KB
/
.prettier.plugin.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
const { parsers } = require('prettier-plugin-organize-imports');
function createParser(original, transform) {
return {
...original,
parse: (text, parsers, options) => {
const ast = original.parse(text, parsers, options);
transform(ast, { ...options, text });
return ast;
},
};
}
// https://lihautan.com/manipulating-ast-with-javascript/
function visit(ast, callbackMap) {
function _visit(node, parent, key, index) {
if (typeof callbackMap === 'function') {
if (callbackMap(node, parent, key, index) === false) {
return;
}
} else if (node.type in callbackMap) {
if (callbackMap[node.type](node, parent, key, index) === false) {
return;
}
}
const keys = Object.keys(node);
for (let i = 0; i < keys.length; i++) {
const child = node[keys[i]];
if (Array.isArray(child)) {
for (let j = 0; j < child.length; j++) {
if (child[j] !== null) {
_visit(child[j], node, keys[i], j);
}
}
} else if (typeof child?.type === 'string') {
_visit(child, node, keys[i], i);
}
}
}
_visit(ast);
}
function transformJavaScript(ast, options) {
if (!options.text.includes('// sort-object-keys')) return;
visit(ast, {
ObjectExpression(node) {
const { properties } = node;
properties.sort((a, b) => {
const { key: aKey } = a;
const { key: bKey } = b;
if (aKey.type === 'Identifier' && bKey.type === 'Identifier') {
return aKey.name.localeCompare(bKey.name);
}
return 0;
});
},
TSTypeLiteral(node) {
const { members } = node;
members.sort((a, b) => {
const { key: aKey } = a;
const { key: bKey } = b;
if (aKey.type === 'Identifier' && bKey.type === 'Identifier') {
return aKey.name.localeCompare(bKey.name);
}
return 0;
});
},
});
}
exports.parsers = {
...parsers,
typescript: createParser(parsers.typescript, transformJavaScript),
};