Skip to content

Commit

Permalink
chore: provide option to pass Svelte compiler path (#471)
Browse files Browse the repository at this point in the history
Tooling can use this to work around some Svelte major version differences
  • Loading branch information
dummdidumm authored Nov 11, 2024
1 parent 10d387a commit 9010a44
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface PluginConfig {
svelteBracketNewLine?: boolean;
svelteAllowShorthand?: boolean;
svelteIndentScriptAndStyle?: boolean;
svelte5CompilerPath?: string;
}

export type PrettierConfig = PluginConfig & Config;
Expand Down
22 changes: 18 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,22 @@ export const languages: Partial<SupportLanguage>[] = [
export const parsers: Record<string, Parser> = {
svelte: {
hasPragma,
parse: (text) => {
parse: async (text, options: ParserOptions) => {
try {
return <ASTNode>{ ...parse(text), __isRoot: true };
let _parse = parse;
if (options.svelte5CompilerPath) {
try {
_parse = (await import(options.svelte5CompilerPath)).parse;
} catch (e) {
console.warn(
`Failed to load Svelte 5 compiler from ${options.svelte5CompilerPath}`,
);
console.warn(e);
options.svelte5CompilerPath = undefined;
}
}

return <ASTNode>{ ..._parse(text), __isRoot: true };
} catch (err: any) {
if (err.start != null && err.end != null) {
// Prettier expects error objects to have loc.start and loc.end fields.
Expand All @@ -57,8 +70,9 @@ export const parsers: Record<string, Parser> = {
// Therefore we do it ourselves here.
options.originalText = text;
// Only Svelte 5 can have TS in the template
options._svelte_ts = isSvelte5Plus && result.isTypescript;
options._svelte_is5Plus = isSvelte5Plus;
const is = !!options.svelte5CompilerPath || isSvelte5Plus;
options._svelte_ts = is && result.isTypescript;
options._svelte_is5Plus = is;
return text;
},
locStart,
Expand Down
6 changes: 6 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ function makeChoice(choice: string) {
}

export const options: Record<keyof PluginConfig, SupportOption> = {
svelte5CompilerPath: {
category: 'Svelte',
type: 'string',
default: '',
description: 'Only set this when using Svelte 5! Path to the Svelte 5 compiler',
},
svelteSortOrder: {
category: 'Svelte',
type: 'choice',
Expand Down

0 comments on commit 9010a44

Please sign in to comment.