跳至主要內容

svelte/compiler

import {
	const VERSION: string

The current version, as set in package.json.

https://svelte.dev.org.tw/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

盡最大努力將 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;
  • 預設 false

如果為 true,則告知編譯器產生自訂元素建構子,而不是常規的 Svelte 元件。

accessors?: boolean;
  • 預設 false
  • 已過時 這在符文模式下將不起作用

如果為 true,將會為元件的 props 建立 getter 和 setter。如果為 false,則僅會為唯讀匯出值建立 (例如,使用 constclassfunction 宣告的值)。如果使用 customElement: true 進行編譯,則此選項預設為 true

namespace?: Namespace;
  • 預設 'html'

元素的命名空間;例如,"html""svg""mathml"

immutable?: boolean;
  • 預設 false
  • 已過時 這在符文模式下將不起作用

如果為 true,則告知編譯器您承諾不會變更任何物件。這使其在檢查值是否已變更時可以不那麼保守。

css?: 'injected' | 'external';
  • 'injected':當使用 render(...) 時,樣式將包含在 head 中,並在元件掛載時注入到文件中 (如果尚未存在)。對於編譯為自訂元素的元件,樣式將注入到 shadow root 中。
  • 'external':CSS 只會返回到編譯結果的 css 欄位中。大多數 Svelte 捆綁器外掛程式會將其設定為 'external' 並使用靜態產生的 CSS 以獲得更好的效能,因為這會產生更小的 JavaScript 捆綁包,並且輸出可以作為可快取的 .css 檔案提供。當使用 customElement 模式進行編譯時,這始終為 'injected'
cssHash?: CssHashGetter;
  • 預設 undefined

一個接收 { hash, css, name, filename } 引數並返回用作作用域 CSS 的類別名稱的字串的函數。它預設為返回 svelte-${hash(css)}

preserveComments?: boolean;
  • 預設 false

如果為 true,您的 HTML 註解將會保留在輸出中。預設情況下,它們會被刪除。

preserveWhitespace?: boolean;
  • 預設 false

如果為 true,元素內部和之間的空白會保留為您輸入的樣子,而不是在可能的情況下刪除或摺疊為單一空格。

runes?: boolean | undefined;
  • 預設 undefined

設定為 true 可強制編譯器進入符文模式,即使沒有符文使用跡象。設定為 false 可強制編譯器忽略符文,即使有符文使用跡象。設定為 undefined (預設值) 可從元件程式碼推斷符文模式。對於使用 Svelte 編譯的 JS/TS 模組,始終為 true。將在 Svelte 6 中預設為 true。請注意,在 svelte.config.js 中將其設定為 true 將強制整個專案 (包括 node_modules 中的元件) 進入符文模式,這可能不是您想要的。如果您正在使用 Vite,請考慮改用 dynamicCompileOptions

discloseVersion?: boolean;
  • 預設 true

如果為 true,則透過將其新增到全域 window.__svelte.v 中儲存的 Set 來在瀏覽器中公開 Svelte 主要版本。

compatibility?: {}
  • 已過時 僅在遷移程式碼之前作為臨時解決方案使用這些
componentApi?: 4 | 5;
  • 預設 5

套用轉換,使 Svelte 檔案的預設匯出仍然可以像在 Svelte 4 中一樣實例化 — 當為瀏覽器編譯時作為一個類別 (如同使用 svelte/legacy 中的 createClassComponent(MyComponent, {...}) 一樣) 或當為伺服器編譯時作為具有 .render(...) 方法的物件

sourcemap?: object | string;
  • 預設 null

將會合併到最終輸出 sourcemap 的初始 sourcemap。這通常是預處理器 sourcemap。

outputFilename?: string;
  • 預設 null

用於您的 JavaScript sourcemap。

cssOutputFilename?: string;
  • 預設 null

用於您的 CSS sourcemap。

hmr?: boolean;
  • 預設 false

如果為 true,則編譯具有熱重載支援的元件。

modernAst?: boolean;
  • 預設 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;
  • 預設 false

如果為 true,會新增額外的程式碼,這些程式碼將在開發期間執行執行階段檢查並提供偵錯資訊。

generate?: 'client' | 'server' | false;
  • 預設 'client'

如果為 "client",Svelte 會發出設計為在瀏覽器中執行的程式碼。如果為 "server",Svelte 會發出適用於伺服器端渲染的程式碼。如果為 false,則不會產生任何內容。對於僅對警告感興趣的工具很有用。

filename?: string;

用於偵錯提示和 sourcemap。您的捆綁器外掛程式會自動設定它。

rootDir?: string;
  • 預設 在類節點環境上為 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;

Processed

預處理器執行的結果。如果預處理器未返回結果,則假定程式碼未變更。

interface Processed {}
code: string;

新的程式碼

map?: string | object;

一個對應回原始程式碼的來源地圖

dependencies?: string[];

一個用於監看變更的額外檔案清單

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

僅適用於腳本/樣式預處理器:要在標籤上設定的更新屬性。如果未定義,則屬性保持不變。

toString?: () => string;

警告

interface Warning extends ICompileDiagnostic {}

在 GitHub 上編輯此頁面

上一頁 下一頁