|
1 | | -import { readFileSync, existsSync } from "fs"; |
| 1 | +import { readFile } from "fs/promises"; |
2 | 2 | import { join } from "path"; |
| 3 | +import { resolveConfig, format, Options } from "prettier"; |
3 | 4 | import { cwd } from "process"; |
4 | | -import { format as prettierFormat, Options } from "prettier"; |
5 | 5 |
|
6 | | -const prettierConfigWidgetPath = join(cwd(), "prettier.config.js"); |
7 | 6 | const prettierConfigBasePath = join(__dirname, "../../configs/prettier.base.json"); |
8 | 7 |
|
9 | | -let prettierConfigBase: object; |
10 | | -if (existsSync(prettierConfigWidgetPath)) { |
11 | | - prettierConfigBase = require(prettierConfigWidgetPath); |
12 | | -} else { |
13 | | - prettierConfigBase = JSON.parse(readFileSync(prettierConfigBasePath, "utf-8")); |
14 | | -} |
| 8 | +let prettierTypescriptConfig: Options | undefined; |
| 9 | + |
| 10 | +/** |
| 11 | + * Uses prettier to format the given TypeScript sourcecode. |
| 12 | + * @param source The TypeScript snippet that needs to be formatted |
| 13 | + */ |
| 14 | +export async function formatTypeScript(source: string): Promise<string> { |
| 15 | + if (prettierTypescriptConfig === undefined) { |
| 16 | + const fakeFilename = join(cwd(), "./src/widget.ts"); |
| 17 | + // If the widget does not have a prettier config, fall back to packaged base config |
| 18 | + const prettierConfig = |
| 19 | + (await resolveConfig(fakeFilename)) ?? JSON.parse(await readFile(prettierConfigBasePath, "utf-8")); |
15 | 20 |
|
16 | | -const prettierConfig: Options = { |
17 | | - ...prettierConfigBase, |
18 | | - parser: "babel-ts" |
19 | | -}; |
| 21 | + prettierTypescriptConfig = { |
| 22 | + ...prettierConfig, |
| 23 | + parser: "babel-ts" |
| 24 | + }; |
| 25 | + } |
20 | 26 |
|
21 | | -export function formatTypescript(source: string): Promise<string> { |
22 | | - return prettierFormat(source, prettierConfig); |
| 27 | + return await format(source, prettierTypescriptConfig); |
23 | 28 | } |
0 commit comments