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

chore: provide option to pass Svelte compiler #471

Merged
merged 2 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from all 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 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
Loading