Skip to content

Commit

Permalink
feat(prettier): Allow a Prettier instance to be optional (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
Princesseuh committed Mar 4, 2024
1 parent c7a2d97 commit 2bb1ad1
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions packages/prettier/index.ts
Expand Up @@ -44,6 +44,10 @@ export function create(
*/
prettier?: typeof import('prettier') | undefined;
getPrettier?: (serviceEnv: ServiceEnvironment) => typeof import('prettier') | undefined,
/**
* If true, the plugin will not throw an error if it can't load Prettier either through the `prettier`, or `getPrettier` properties or through a normal `import('prettier')`.
*/
allowImportError?: boolean;
} = {},
getPrettierConfig = async (filePath: string, prettier: typeof import('prettier'), config?: ResolveConfigOptions) => {
return await prettier.resolveConfig(filePath, config) ?? {};
Expand All @@ -52,16 +56,28 @@ export function create(
return {
name: 'prettier',
create(context): ServicePluginInstance {
const languages = options.languages ?? ['html', 'css', 'scss', 'typescript', 'javascript'];

let prettier: typeof import('prettier');
let _prettier = options.prettier;
try {
prettier = options.prettier
?? options.getPrettier?.(context.env)
?? require('prettier');
} catch (e) {
throw new Error("Could not load Prettier: " + e);
if (!_prettier) {
if (options.getPrettier) {
_prettier = options.getPrettier(context.env);
} else {
_prettier = require('prettier');
}
}
} catch (error) {
if (!options.allowImportError) {
throw new Error("Could not load Prettier: ");
};
}
const languages = options.languages ?? ['html', 'css', 'scss', 'typescript', 'javascript'];

if (!_prettier) {
return {};
}

const prettier = _prettier;

return {
async provideDocumentFormattingEdits(document, _, formatOptions) {
Expand Down

0 comments on commit 2bb1ad1

Please sign in to comment.