メインコンテンツにスキップ

svelte/compiler

import {
	const VERSION: string

The current version, as set in package.json.

https://svelte.dokyumento.jp/docs/svelte-compiler#svelte-version

VERSION
,
function compile(source: string, options: CompileOptions): CompileResult

compile converts your .svelte source code into a JavaScript module that exports a component

@paramsource The component source code
@paramoptions The compiler options
compile
,
function compileModule(source: string, options: ModuleCompileOptions): CompileResult

compileModule takes your JavaScript source code containing runes, and turns it into a JavaScript module.

@paramsource The component source code
compileModule
,
function migrate(source: string, { filename, use_ts }?: {
    filename?: string;
    use_ts?: boolean;
} | undefined): {
    code: string;
}

Does a best-effort migration of Svelte code towards using runes, event attributes and render tags. May throw an error if the code is too complex to migrate automatically.

migrate
,
function parse(source: string, options: {
    filename?: string;
    modern: true;
}): AST.Root (+1 overload)

The parse function parses a component, returning only its abstract syntax tree.

The modern option (false by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST. modern will become true by default in Svelte 6, and the option will be removed in Svelte 7.

parse
,
function preprocess(source: string, preprocessor: PreprocessorGroup | PreprocessorGroup[], options?: {
    filename?: string;
} | undefined): Promise<Processed>

The preprocess function provides convenient hooks for arbitrarily transforming component source code. For example, it can be used to convert a &#x3C;style lang="sass"> block into vanilla CSS.

preprocess
,
function walk(): never
@deprecatedReplace this with import { walk } from 'estree-walker'
walk
} from 'svelte/compiler';

VERSION

package.json で設定されている現在のバージョン。

/docs/svelte-compiler#svelte-version

const VERSION: string;

compile

compile.svelte ソースコードを、コンポーネントをエクスポートする JavaScript モジュールに変換します

function compile(
	source: string,
	options: CompileOptions
): CompileResult;

compileModule

compileModule はルーンを含む JavaScript ソースコードを受け取り、それを JavaScript モジュールに変換します。

function compileModule(
	source: string,
	options: ModuleCompileOptions
): CompileResult;

migrate

ルーン、イベント属性、renderタグを使用するように、Svelteコードを最大限に移行します。コードが複雑すぎて自動的に移行できない場合は、エラーをスローする可能性があります。

function migrate(
	source: string,
	{
		filename,
		use_ts
	}?:
		| {
				filename?: string;
				use_ts?: boolean;
		  }
		| undefined
): {
	code: string;
};

parse

parse関数はコンポーネントを解析し、その抽象構文木のみを返します。

modern オプション (Svelte 5 ではデフォルトで false) を指定すると、パーサーはレガシー AST の代わりに最新の AST を返します。modern は Svelte 6 でデフォルトで true になり、このオプションは Svelte 7 で削除されます。

function parse(
	source: string,
	options: {
		filename?: string;
		modern: true;
	}
): AST.Root;
function parse(
	source: string,
	options?:
		| {
				filename?: string;
				modern?: false;
		  }
		| undefined
): Record<string, any>;

preprocess

preprocess 関数は、コンポーネントのソースコードを任意に変換するための便利なフックを提供します。たとえば、<style lang="sass"> ブロックをバニラ CSS に変換するために使用できます。

function preprocess(
	source: string,
	preprocessor: PreprocessorGroup | PreprocessorGroup[],
	options?:
		| {
				filename?: string;
		  }
		| undefined
): Promise<Processed>;

walk

import { walk } from 'estree-walker' で置き換えてください

function walk(): never;

AST

namespace AST {
	export interface BaseNode {
		type: string;
		start: number;
		end: number;
	}

	export interface Fragment {
		type: 'Fragment';
		nodes: Array<
			Text | Tag | ElementLike | Block | Comment
		>;
	}

	export interface Root extends BaseNode {
		type: 'Root';
		/**
		 * Inline options provided by `<svelte:options>` — these override options passed to `compile(...)`
		 */
		options: SvelteOptions | null;
		fragment: Fragment;
		/** The parsed `<style>` element, if exists */
		css: Css.StyleSheet | null;
		/** The parsed `<script>` element, if exists */
		instance: Script | null;
		/** The parsed `<script module>` element, if exists */
		module: Script | null;
	}

	export interface SvelteOptions {
		// start/end info (needed for warnings and for our Prettier plugin)
		start: number;
		end: number;
		// options
		runes?: boolean;
		immutable?: boolean;
		accessors?: boolean;
		preserveWhitespace?: boolean;
		namespace?: Namespace;
		css?: 'injected';
		customElement?: {
			tag?: string;
			shadow?: 'open' | 'none';
			props?: Record<
				string,
				{
					attribute?: string;
					reflect?: boolean;
					type?:
						| 'Array'
						| 'Boolean'
						| 'Number'
						| 'Object'
						| 'String';
				}
			>;
			/**
			 * Is of type
			 * ```ts
			 * (ceClass: new () => HTMLElement) => new () => HTMLElement
			 * ```
			 */
			extend?: ArrowFunctionExpression | Identifier;
		};
		attributes: Attribute[];
	}

	/** Static text */
	export interface Text extends BaseNode {
		type: 'Text';
		/** Text with decoded HTML entities */
		data: string;
		/** The original text, with undecoded HTML entities */
		raw: string;
	}

	/** A (possibly reactive) template expression — `{...}` */
	export interface ExpressionTag extends BaseNode {
		type: 'ExpressionTag';
		expression: Expression;
	}

	/** A (possibly reactive) HTML template expression — `{@html ...}` */
	export interface HtmlTag extends BaseNode {
		type: 'HtmlTag';
		expression: Expression;
	}

	/** An HTML comment */
	// TODO rename to disambiguate
	export interface Comment extends BaseNode {
		type: 'Comment';
		/** the contents of the comment */
		data: string;
	}

	/** A `{@const ...}` tag */
	export interface ConstTag extends BaseNode {
		type: 'ConstTag';
		declaration: VariableDeclaration & {
			declarations: [
				VariableDeclarator & {
					id: Pattern;
					init: Expression;
				}
			];
		};
	}

	/** A `{@debug ...}` tag */
	export interface DebugTag extends BaseNode {
		type: 'DebugTag';
		identifiers: Identifier[];
	}

	/** A `{@render foo(...)} tag */
	export interface RenderTag extends BaseNode {
		type: 'RenderTag';
		expression:
			| SimpleCallExpression
			| (ChainExpression & {
					expression: SimpleCallExpression;
			  });
	}

	/** An `animate:` directive */
	export interface AnimateDirective extends BaseNode {
		type: 'AnimateDirective';
		/** The 'x' in `animate:x` */
		name: string;
		/** The y in `animate:x={y}` */
		expression: null | Expression;
	}

	/** A `bind:` directive */
	export interface BindDirective extends BaseNode {
		type: 'BindDirective';
		/** The 'x' in `bind:x` */
		name: string;
		/** The y in `bind:x={y}` */
		expression: Identifier | MemberExpression;
	}

	/** A `class:` directive */
	export interface ClassDirective extends BaseNode {
		type: 'ClassDirective';
		/** The 'x' in `class:x` */
		name: 'class';
		/** The 'y' in `class:x={y}`, or the `x` in `class:x` */
		expression: Expression;
	}

	/** A `let:` directive */
	export interface LetDirective extends BaseNode {
		type: 'LetDirective';
		/** The 'x' in `let:x` */
		name: string;
		/** The 'y' in `let:x={y}` */
		expression:
			| null
			| Identifier
			| ArrayExpression
			| ObjectExpression;
	}

	/** An `on:` directive */
	export interface OnDirective extends BaseNode {
		type: 'OnDirective';
		/** The 'x' in `on:x` */
		name: string;
		/** The 'y' in `on:x={y}` */
		expression: null | Expression;
		modifiers: string[];
	}

	/** A `style:` directive */
	export interface StyleDirective extends BaseNode {
		type: 'StyleDirective';
		/** The 'x' in `style:x` */
		name: string;
		/** The 'y' in `style:x={y}` */
		value:
			| true
			| ExpressionTag
			| Array<ExpressionTag | Text>;
		modifiers: Array<'important'>;
	}

	// TODO have separate in/out/transition directives
	/** A `transition:`, `in:` or `out:` directive */
	export interface TransitionDirective extends BaseNode {
		type: 'TransitionDirective';
		/** The 'x' in `transition:x` */
		name: string;
		/** The 'y' in `transition:x={y}` */
		expression: null | Expression;
		modifiers: Array<'local' | 'global'>;
		/** True if this is a `transition:` or `in:` directive */
		intro: boolean;
		/** True if this is a `transition:` or `out:` directive */
		outro: boolean;
	}

	/** A `use:` directive */
	export interface UseDirective extends BaseNode {
		type: 'UseDirective';
		/** The 'x' in `use:x` */
		name: string;
		/** The 'y' in `use:x={y}` */
		expression: null | Expression;
	}

	interface BaseElement extends BaseNode {
		name: string;
		attributes: Array<
			Attribute | SpreadAttribute | Directive
		>;
		fragment: Fragment;
	}

	export interface Component extends BaseElement {
		type: 'Component';
	}

	export interface TitleElement extends BaseElement {
		type: 'TitleElement';
		name: 'title';
	}

	export interface SlotElement extends BaseElement {
		type: 'SlotElement';
		name: 'slot';
	}

	export interface RegularElement extends BaseElement {
		type: 'RegularElement';
	}

	export interface SvelteBody extends BaseElement {
		type: 'SvelteBody';
		name: 'svelte:body';
	}

	export interface SvelteComponent extends BaseElement {
		type: 'SvelteComponent';
		name: 'svelte:component';
		expression: Expression;
	}

	export interface SvelteDocument extends BaseElement {
		type: 'SvelteDocument';
		name: 'svelte:document';
	}

	export interface SvelteElement extends BaseElement {
		type: 'SvelteElement';
		name: 'svelte:element';
		tag: Expression;
	}

	export interface SvelteFragment extends BaseElement {
		type: 'SvelteFragment';
		name: 'svelte:fragment';
	}

	export interface SvelteBoundary extends BaseElement {
		type: 'SvelteBoundary';
		name: 'svelte:boundary';
	}

	export interface SvelteHead extends BaseElement {
		type: 'SvelteHead';
		name: 'svelte:head';
	}

	/** This is only an intermediate representation while parsing, it doesn't exist in the final AST */
	export interface SvelteOptionsRaw extends BaseElement {
		type: 'SvelteOptions';
		name: 'svelte:options';
	}

	export interface SvelteSelf extends BaseElement {
		type: 'SvelteSelf';
		name: 'svelte:self';
	}

	export interface SvelteWindow extends BaseElement {
		type: 'SvelteWindow';
		name: 'svelte:window';
	}

	/** An `{#each ...}` block */
	export interface EachBlock extends BaseNode {
		type: 'EachBlock';
		expression: Expression;
		/** The `entry` in `{#each item as entry}`. `null` if `as` part is omitted */
		context: Pattern | null;
		body: Fragment;
		fallback?: Fragment;
		index?: string;
		key?: Expression;
	}

	/** An `{#if ...}` block */
	export interface IfBlock extends BaseNode {
		type: 'IfBlock';
		elseif: boolean;
		test: Expression;
		consequent: Fragment;
		alternate: Fragment | null;
	}

	/** An `{#await ...}` block */
	export interface AwaitBlock extends BaseNode {
		type: 'AwaitBlock';
		expression: Expression;
		// TODO can/should we move these inside the ThenBlock and CatchBlock?
		/** The resolved value inside the `then` block */
		value: Pattern | null;
		/** The rejection reason inside the `catch` block */
		error: Pattern | null;
		pending: Fragment | null;
		then: Fragment | null;
		catch: Fragment | null;
	}

	export interface KeyBlock extends BaseNode {
		type: 'KeyBlock';
		expression: Expression;
		fragment: Fragment;
	}

	export interface SnippetBlock extends BaseNode {
		type: 'SnippetBlock';
		expression: Identifier;
		parameters: Pattern[];
		body: Fragment;
	}

	export interface Attribute extends BaseNode {
		type: 'Attribute';
		name: string;
		/**
		 * Quoted/string values are represented by an array, even if they contain a single expression like `"{x}"`
		 */
		value:
			| true
			| ExpressionTag
			| Array<Text | ExpressionTag>;
	}

	export interface SpreadAttribute extends BaseNode {
		type: 'SpreadAttribute';
		expression: Expression;
	}

	export interface Script extends BaseNode {
		type: 'Script';
		context: 'default' | 'module';
		content: Program;
		attributes: Attribute[];
	}
}

CompileError

interface CompileError extends ICompileDiagnostic {}

CompileOptions

interface CompileOptions extends ModuleCompileOptions {}
name?: string;

結果として得られる JavaScript クラスの名前を設定します(ただし、コンパイラーは、スコープ内の他の変数と競合する場合は名前を変更します)。指定しない場合は、filename から推論されます

customElement?: boolean;
  • default false

true の場合、コンパイラーは、通常の Svelte コンポーネントの代わりにカスタム要素コンストラクターを生成するように指示します。

accessors?: boolean;
  • default false
  • 非推奨 ルーンモードでは効果がありません

true の場合、コンポーネントの props 用に getter と setter が作成されます。false の場合、読み取り専用のエクスポートされた値 (つまり、constclassfunction で宣言されたもの) に対してのみ作成されます。customElement: true でコンパイルする場合、このオプションのデフォルトは true です。

namespace?: Namespace;
  • default 'html'

要素の名前空間。例:"html""svg""mathml"

immutable?: boolean;
  • default false
  • 非推奨 ルーンモードでは効果がありません

true の場合、オブジェクトをミューテートしないことをコンパイラーに約束します。これにより、値が変更されたかどうかをチェックする際に、より保守的でなくなることができます。

css?: 'injected' | 'external';
  • 'injected': スタイルは render(...) を使用すると head に含まれ、コンポーネントがマウントされると(まだ存在しない場合)ドキュメントに挿入されます。カスタム要素としてコンパイルされたコンポーネントの場合、スタイルはシャドウルートに挿入されます。
  • 'external': CSS はコンパイル結果の css フィールドでのみ返されます。ほとんどの Svelte バンドラープラグインはこれを 'external' に設定し、静的に生成された CSS を使用してパフォーマンスを向上させます。これにより、JavaScript バンドルが小さくなり、出力がキャッシュ可能な .css ファイルとして提供されるためです。customElement モードでコンパイルする場合は常に 'injected' になります。
cssHash?: CssHashGetter;
  • default undefined

{ hash, css, name, filename } 引数を受け取り、スコープ付き CSS のクラス名として使用される文字列を返す関数。デフォルトでは svelte-${hash(css)} を返します。

preserveComments?: boolean;
  • default false

true の場合、HTML コメントは出力に保持されます。デフォルトでは、それらは削除されます。

preserveWhitespace?: boolean;
  • default false

true の場合、要素の内側と要素間の空白は、可能な限り削除されたり、単一のスペースに折りたたまれたりせずに、入力したとおりに保持されます。

runes?: boolean | undefined;
  • default undefined

ルーンの使用を示す兆候がない場合でも、コンパイラーを強制的にルーンモードにするには true に設定します。ルーンの使用を示す兆候がある場合でも、コンパイラーがルーンを無視するように強制するには false に設定します。コンポーネントコードからルーンモードを推論するには、undefined(デフォルト)に設定します。Svelte でコンパイルされた JS/TS モジュールの場合、常に true です。Svelte 6 ではデフォルトで true になります。svelte.config.js でこれを true に設定すると、node_modules 内のコンポーネントを含むプロジェクト全体でルーンモードが強制されるため、望ましくない可能性があります。Vite を使用している場合は、代わりに dynamicCompileOptions を使用することを検討してください。

discloseVersion?: boolean;
  • default true

true の場合、グローバル window.__svelte.v に格納された Set に追加することにより、ブラウザーで Svelte のメジャーバージョンを公開します。

compatibility?: {}
  • 非推奨 コードを移行するまでの一時的な解決策としてのみ使用してください
componentApi?: 4 | 5;
  • default 5

Svelte ファイルのデフォルトエクスポートが、Svelte 4 と同じ方法でインスタンス化できるように変換を適用します。ブラウザー用にコンパイルする場合はクラスとして(svelte/legacy から createClassComponent(MyComponent, {...}) を使用したかのように)、サーバー用にコンパイルする場合は .render(...) メソッドを持つオブジェクトとして。

sourcemap?: object | string;
  • default null

最終的な出力ソースマップにマージされる初期ソースマップ。通常、これはプリプロセッサのソースマップです。

outputFilename?: string;
  • default null

JavaScript ソースマップに使用されます。

cssOutputFilename?: string;
  • default null

CSS ソースマップに使用されます。

hmr?: boolean;
  • default false

true の場合、ホットリロードをサポートするコンポーネントをコンパイルします。

modernAst?: boolean;
  • default false

true の場合、AST の最新バージョンを返します。Svelte 6 ではデフォルトで true になり、このオプションは Svelte 7 で削除されます。

CompileResult

svelte/compilercompile の戻り値

interface CompileResult {}
js: {}

コンパイルされた JavaScript

code: string;

生成されたコード

map: SourceMap;

ソースマップ

css: null | {
	/** The generated code */
	code: string;
	/** A source map */
	map: SourceMap;
};

コンパイルされた CSS

warnings: Warning[];

コンパイル中に生成された警告オブジェクトの配列。各警告にはいくつかのプロパティがあります

  • code は警告のカテゴリを識別する文字列です
  • message は問題を人間が読める形式で説明します
  • 警告が特定の場所に��関連している場合、startend は、linecolumncharacter プロパティを持つオブジェクトです
metadata: {}

コンパイルされたコンポーネントに関するメタデータ

runes: boolean;

明示的なオプションまたは使用状況から推論された結果として、ファイルがルーンモードでコンパイルされたかどうか。compileModule の場合、これは常に true です

ast: any;

AST

MarkupPreprocessor

コードの文字列を受け取り、処理されたバージョンを返すマークアッププリプロセッサ。

type MarkupPreprocessor = (options: {
	/**
	 * The whole Svelte file content
	 */
	content: string;
	/**
	 * The filename of the Svelte file
	 */
	filename?: string;
}) => Processed | void | Promise<Processed | void>;

ModuleCompileOptions

interface ModuleCompileOptions {}
dev?: boolean;
  • default false

true の場合、開発中にランタイムチェックを実行し、デバッグ情報を提供する追加のコードが追加されます。

generate?: 'client' | 'server' | false;
  • default 'client'

"client" の場合、Svelte はブラウザーで実行するように設計されたコードを出力します。"server" の場合、Svelte はサーバーサイドレンダリングに適したコードを出力します。false の場合、何も生成されません。警告のみに関心のあるツールに役立ちます。

filename?: string;

デバッグのヒントとソースマップに使用されます。バンドラープラグインによって自動的に設定されます。

rootDir?: string;
  • default node のような環境では process.cwd()、それ以外の場合は undefined

ファイル名がファイルシステム情報を漏洩しないようにするために使用されます。バンドラープラグインによって自動的に設定されます。

warningFilter?: (warning: Warning) => boolean;

Warning を引数として受け取り、ブール値を返す関数。これを使用して警告をフィルタリングします。警告を保持するには true を返し、破棄するには false を返します。

Preprocessor

コードの文字列を受け取り、処理されたバージョンを返すスクリプト/スタイルプリプロセッサ。

type Preprocessor = (options: {
	/**
	 * The script/style tag content
	 */
	content: string;
	/**
	 * The attributes on the script/style tag
	 */
	attributes: Record<string, string | boolean>;
	/**
	 * The whole Svelte file content
	 */
	markup: string;
	/**
	 * The filename of the Svelte file
	 */
	filename?: string;
}) => Processed | void | Promise<Processed | void>;

PreprocessorGroup

プリプロセッサグループとは、Svelteファイルに適用されるプリプロセッサの集合です。

interface PreprocessorGroup {}
name?: string;

プリプロセッサの名前。次のメジャーバージョンでは必須オプションになります。

markup?: MarkupPreprocessor;
style?: Preprocessor;
script?: Preprocessor;

処理済み

プリプロセッサ実行の結果。プリプロセッサが結果を返さない場合、コードは変更されていないとみなされます。

interface Processed {}
code: string;

新しいコード

map?: string | object;

元のコードへのマッピングを示すソースマップ

dependencies?: string[];

変更を監視する追加ファイルのリスト

attributes?: Record<string, string | boolean>;

script/styleプリプロセッサのみ:タグに設定する更新された属性。未定義の場合、属性は変更されません。

toString?: () => string;

警告

interface Warning extends ICompileDiagnostic {}

GitHubでこのページを編集