From c14c3958a9adaa26d2d3bd52bd9518981dc0aa3e Mon Sep 17 00:00:00 2001 From: Simon Holthausen Date: Sat, 9 Nov 2024 20:57:04 +0100 Subject: [PATCH] fix: use user's Svelte parser when formatting if necessary This makes formatting "just work" if users use Svelte 5 but don't have prettier (and the plugin) installed in their workspace Depends on https://github.com/sveltejs/prettier-plugin-svelte/pull/471 --- .../src/plugins/svelte/SveltePlugin.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/language-server/src/plugins/svelte/SveltePlugin.ts b/packages/language-server/src/plugins/svelte/SveltePlugin.ts index f3d941716..3fe7c49a5 100644 --- a/packages/language-server/src/plugins/svelte/SveltePlugin.ts +++ b/packages/language-server/src/plugins/svelte/SveltePlugin.ts @@ -127,11 +127,9 @@ export class SveltePlugin /** * Prettier v2 can't use v3 plugins and vice versa. Therefore, we need to check * which version of prettier is used in the workspace and import the correct - * version of the Svelte plugin. If user uses Prettier >= 3 and has no Svelte plugin - * then fall back to our built-in versions which are both v2 and compatible with + * version of the Svelte plugin. If user uses Prettier < 3 and has no Svelte plugin + * then fall back to our built-in versions which are both v3 and compatible with * each other. - * TODO switch this around at some point to load Prettier v3 by default because it's - * more likely that users have that installed. */ const importFittingPrettier = async () => { const getConfig = async (p: any) => { @@ -206,6 +204,15 @@ export class SveltePlugin return []; } + if (isFallback || !(await hasSveltePluginLoaded(prettier, resolvedPlugins))) { + // If the user uses Svelte 5 but doesn't have prettier installed, we need to provide + // the compiler path to the plugin so it can use its parser method; else it will crash. + const svelteCompilerInfo = getPackageInfo('svelte', filePath); + if (svelteCompilerInfo.version.major >= 5) { + config.svelte5CompilerPath = svelteCompilerInfo.path + '/compiler'; + } + } + // Prettier v3 format is async, v2 is not const formattedCode = await prettier.format(document.getText(), { ...config,