Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(prettier): Allow a Prettier instance to be optional #81

Merged
merged 5 commits into from Mar 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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