Skip to content

Commit

Permalink
fix: use user's Svelte parser when formatting if necessary (#2578)
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

#2542
  • Loading branch information
dummdidumm authored Nov 11, 2024
1 parent bf1b8ef commit 437b0e1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
2 changes: 1 addition & 1 deletion packages/language-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"globrex": "^0.1.2",
"lodash": "^4.17.21",
"prettier": "~3.3.3",
"prettier-plugin-svelte": "^3.2.6",
"prettier-plugin-svelte": "^3.2.8",
"svelte": "^4.2.19",
"svelte2tsx": "workspace:~",
"typescript": "^5.6.3",
Expand Down
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
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 437b0e1

Please sign in to comment.