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
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ node_modules
*.js
*.map
*.tgz
.DS_Store
johnsoncodehk marked this conversation as resolved.
Show resolved Hide resolved
29 changes: 22 additions & 7 deletions packages/prettier/index.ts
Original file line number Diff line number Diff line change
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,19 +56,30 @@ 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: ");
};
}

johnsoncodehk marked this conversation as resolved.
Show resolved Hide resolved
if (!prettier) {
return {};
}
const languages = options.languages ?? ['html', 'css', 'scss', 'typescript', 'javascript'];

return {
async provideDocumentFormattingEdits(document, _, formatOptions) {
if (!prettier) return;
if (!languages.includes(document.languageId)) {
return;
}
Expand Down