Skip to content

Commit

Permalink
fix: use user's Svelte parser when formatting if necessary
Browse files Browse the repository at this point in the history
This makes formatting "just work" if users use Svelte 5 but don't have prettier (and the plugin) installed in their workspace

Depends on sveltejs/prettier-plugin-svelte#471
  • Loading branch information
dummdidumm committed Nov 9, 2024
1 parent 0698bc7 commit c14c395
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/language-server/src/plugins/svelte/SveltePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit c14c395

Please sign in to comment.