1 | import * as path from 'path';
|
2 | const EXTENSION_TO_PARSER = {
|
3 | ts: 'typescript',
|
4 | tsx: 'typescript',
|
5 | js: 'babylon',
|
6 | jsx: 'babylon',
|
7 | 'js.flow': 'flow',
|
8 | flow: 'flow',
|
9 | gql: 'graphql',
|
10 | graphql: 'graphql',
|
11 | graphqls: 'graphql',
|
12 | css: 'postcss',
|
13 | scss: 'postcss',
|
14 | less: 'postcss',
|
15 | stylus: 'postcss',
|
16 | markdown: 'markdown',
|
17 | md: 'markdown',
|
18 | json: 'json'
|
19 | };
|
20 | export async function prettify(filePath, content) {
|
21 | try {
|
22 | const prettierPath = require.resolve('prettier');
|
23 | if (prettierPath) {
|
24 | const prettier = await import('prettier');
|
25 | const fileExtension = path.extname(filePath).slice(1);
|
26 | const parser = EXTENSION_TO_PARSER[fileExtension];
|
27 | const { ignored } = await prettier.getFileInfo(filePath, { ignorePath: '.prettierignore' });
|
28 | if (ignored) {
|
29 | return content;
|
30 | }
|
31 | const config = await prettier.resolveConfig(filePath, { useCache: true, editorconfig: true });
|
32 | return prettier.format(content, Object.assign({ parser }, (config || {})));
|
33 | }
|
34 | return content;
|
35 | }
|
36 | catch (e) {
|
37 | return content;
|
38 | }
|
39 | }
|
40 |
|
\ | No newline at end of file |