Skip to main content

svelte/compiler

import {
	const VERSION: string

The current version, as set in package.json.

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;
    loose?: boolean;
}): 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';

版本

当前版本,如 package.json 中设置。

const 版本: string;

编译

编译将您的.svelte源代码转换为导出组件的 JavaScript 模块

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

编译模块

compileModule 接收包含符文的 JavaScript 源代码,并将其转换为 JavaScript 模块。

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

迁移

尽力迁移 Svelte 代码以使用 runes、事件属性和渲染标签。如果代码过于复杂而无法自动迁移,可能会抛出错误。

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

解析

函数解析组件,仅返回其抽象语法树。

现代(modern)选项(在 Svelte 5 中默认为 false)使解析器返回现代 AST 而不是传统 AST。《modern 将在 Svelte 6 中默认为 true,并在 Svelte 7 中移除此选项。

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

预处理

预处理函数提供了方便的钩子,用于任意转换组件源代码。例如,它可以用来将一个<style lang="sass">块转换为纯 CSS。

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

替换为此 import { walk } from 'estree-walker'

函数 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: AST.CSS.StyleSheet | null;
		/** The parsed `<script>` element, if exists */
		instance: Script | null;
		/** The parsed `<script module>` element, if exists */
		module: Script | null;
		/** Comments found in <script> and {expressions} */
		comments: JSComment[];
	}

	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;
			  });
	}

	/** A `{@attach foo(...)} tag */
	export interface AttachTag extends BaseNode {
		type: 'AttachTag';
		expression: Expression;
	}

	/** 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
			| SequenceExpression;
	}

	/** 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 | AttachTag
		>;
		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[];
		typeParams?: string;
		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[];
	}

	export interface JSComment {
		type: 'Line' | 'Block';
		value: string;
		start: number;
		end: number;
		loc: {
			start: { line: number; column: number };
			end: { line: number; column: number };
		};
	}

	export type AttributeLike =
		| Attribute
		| SpreadAttribute
		| Directive;

	export type Directive =
		| AST.AnimateDirective
		| AST.BindDirective
		| AST.ClassDirective
		| AST.LetDirective
		| AST.OnDirective
		| AST.StyleDirective
		| AST.TransitionDirective
		| AST.UseDirective;

	export type Block =
		| AST.EachBlock
		| AST.IfBlock
		| AST.AwaitBlock
		| AST.KeyBlock
		| AST.SnippetBlock;

	export type ElementLike =
		| AST.Component
		| AST.TitleElement
		| AST.SlotElement
		| AST.RegularElement
		| AST.SvelteBody
		| AST.SvelteBoundary
		| AST.SvelteComponent
		| AST.SvelteDocument
		| AST.SvelteElement
		| AST.SvelteFragment
		| AST.SvelteHead
		| AST.SvelteOptionsRaw
		| AST.SvelteSelf
		| AST.SvelteWindow
		| AST.SvelteBoundary;

	export type Tag =
		| AST.AttachTag
		| AST.ConstTag
		| AST.DebugTag
		| AST.ExpressionTag
		| AST.HtmlTag
		| AST.RenderTag;

	export type TemplateNode =
		| AST.Root
		| AST.Text
		| Tag
		| ElementLike
		| AST.Attribute
		| AST.SpreadAttribute
		| Directive
		| AST.AttachTag
		| AST.Comment
		| Block;

	export type SvelteNode =
		| Node
		| TemplateNode
		| AST.Fragment
		| _CSS.Node
		| Script;

	export type { _CSS as CSS };
}

编译错误

interface CompileError extends ICompileDiagnostic {}

编译选项

interface CompileOptions extends ModuleCompileOptions {}

name?: 字符串;

设置结果 JavaScript 类的名称(尽管编译器如果与作用域内的其他变量冲突,则会重命名它)。如果未指定,将根据filename推断。

customElement?: boolean;
  • 默认

如果 true,告诉编译器生成一个自定义元素构造函数而不是常规的 Svelte 组件。

accessors?: 布尔型;

  • 默认
  • 已弃用这在符文模式下将没有任何效果

如果 true,将为组件的属性创建获取器和设置器。如果 false,它们将仅针对只读导出值(即使用 constclassfunction 声明的值)创建。如果使用 customElement: true 编译,此选项默认为 true

命名空间?: 命名空间;

  • 默认'html'

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

不可变?: boolean;

  • 默认
  • 已弃用这在符文模式下将没有任何效果

如果 true,告诉编译器你承诺不会修改任何对象。这允许它在检查值是否发生变化时更加保守。

css?: 'injected' | 'external';
  • 注入:使用head时,样式将被包含在内,并在组件挂载时(如果尚未存在)注入到文档中。对于编译为自定义元素的组件,样式将被注入到阴影根中。
  • 'external':CSS 只会在编译结果的 css 字段中返回。大多数 Svelte 打包器插件会将此设置为 'external' 并使用静态生成的 CSS 以提高性能,因为它将导致 JavaScript 打包文件更小,输出可以作为可缓存的 .css 文件提供。在以 customElement 模式编译时,这始终是 'injected'

cssHash?: CssHash 获取器;

  • 默认未定义

一个接受 { hash, css, name, filename } 参数的函数,并返回用作作用域 CSS 的类名的字符串。默认返回 svelte-${hash(css)}

preserveComments?: boolean;
  • 默认

如果 true,您的 HTML 注释将在输出中保留。默认情况下,它们将被删除。

preserveWhitespace?: boolean;
  • 默认

如果 true,则元素内部和元素之间的空白将保持您输入的格式,而不是删除或折叠为尽可能少的单个空格。

片段?: 'html' | 'tree';

  • 默认'html'
  • 自 v5.33 起可用

哪种策略用于克隆 DOM 片段:

  • html 使用 <template> 通过 innerHTML 填充并克隆它。这更快,但如果您的应用的 内容安全策略 包含 require-trusted-types-for 'script' ,则不能使用。
  • 逐个元素创建片段,然后克隆它。这比较慢,但可以在任何地方工作。

runes?: 布尔值 | 未定义;

  • 默认未定义

设置为true以强制编译器进入 runes 模式,即使没有 runes 使用的迹象。设置为false以强制编译器忽略 runes,即使有 runes 使用的迹象。设置为undefined(默认)以从组件代码推断 runes 模式。对于使用 Svelte 编译的 JS/TS 模块,始终为true。在 Svelte 6 中将默认为true。请注意,在您的svelte.config.js中将此设置为true将强制您的整个项目进入 runes 模式,包括node_modules中的组件,这可能是您不希望看到的。如果您使用 Vite,请考虑使用dynamicCompileOptions代替。

discloseVersion?: boolean;
  • 默认

如果 true,则通过将其添加到存储在全局 window.__svelte.v 中的 Set 中,在浏览器中暴露 Svelte 主要版本。

兼容性?: {/*…*/}

  • 已弃用在使用代码迁移之前,请将这些仅作为临时解决方案使用
componentApi?: 4 | 5;
  • 默认5

应用转换,以便 Svelte 文件的默认导出仍然可以像 Svelte 4 一样实例化——在编译为浏览器时作为一个类(就像使用 svelte/legacy 中的 createClassComponent(MyComponent, {...}) 一样)或在编译为服务器时作为一个具有 .render(...) 方法的对象。

source map?: 对象 | 字符串;

  • 默认

一个将被合并到最终输出 sourcemap 中的初始 sourcemap。这通常是预处理 sourcemap。

outputFilename?: 字符串;

  • 默认

用于您的 JavaScript 源映射。

cssOutputFilename?: 字符串;

  • 默认

用于您的 CSS 源映射。

hmr?: 布尔型;

  • 默认

如果 true,则编译具有热重载支持的组件。

modernAst?: 布尔型;

  • 默认

如果 true,则返回 AST 的现代版本。在 Svelte 6 中默认将变为 true,并在 Svelte 7 中移除此选项。

编译结果

返回值来自 compilesvelte/compiler

interface CompileResult {}
js: {}

编译后的 JavaScript

代码:字符串;

生成的代码

映射: SourceMap;

源映射

css: null | {
	/** The generated code */
	code: string;
	/** A source map */
	map: SourceMap;
	/** Whether or not the CSS includes global rules */
	hasGlobal: boolean;
};

编译后的 CSS

警告:警告[];

编译过程中生成的警告对象数组。每个警告具有多个属性:

  • 代码是一个标识警告类别的字符串
  • message用人类可读的术语描述问题
  • 开始结束,如果警告与特定位置相关,则具有 字符 属性的对象
metadata: {}

组件编译元数据

符文:布尔型;

文件是否以 runes 模式编译,无论是由于显式选项还是从使用中推断。对于 compileModule,这始终是 true

ast: 任何

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>;

模块编译选项

interface ModuleCompileOptions {}

dev?: 布尔型;

  • 默认

如果 true,则会在开发期间添加额外的代码,以执行运行时检查并提供调试信息。

generate?: 'client' | 'server' | false;
  • 默认'客户端'

如果 "client",Svelte 会生成在浏览器中运行的代码。如果 "server",Svelte 会生成适合服务器端渲染的代码。如果 false,则不生成任何代码。对于只关注警告的工具来说很有用。

filename?: 字符串;

用于调试提示和源映射。您的打包插件将自动设置它。

rootDir?: 字符串;

  • 默认 process.cwd() on node-like environments, undefined elsewhere

用于确保文件名不会泄露文件系统信息。您的打包插件将自动设置它。

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

一个接收一个 警告 作为参数并返回布尔值的函数。使用此函数来过滤警告。返回 true 保留警告,false 丢弃它。

实验性?: {/*…*/}

  • 自 v5.36 起可用

实验选项

async?: 布尔型;

  • 自 v5.36 起可用

允许在派生类、模板表达式和组件顶层使用 await 关键字

预处理程序

一个将代码字符串处理成处理版本的脚本/样式预处理器。

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>;

预处理组

预处理器组是一组应用于 Svelte 文件的预处理器。

interface PreprocessorGroup {}

name?: 字符串;

预处理器的名称。将在下一个主要版本中成为必选选项

标记?: 标记预处理器;

样式?: 预处理器;

脚本?: 预处理器;

处理完毕

预处理程序运行的结果。如果预处理程序不返回结果,则假定代码未更改。

处理后的接口 {/*…*/}

代码:字符串;

新代码

map?: 字符串 | 对象;

源映射回原始代码

dependencies?: 字符串数组;

一个需要监视变更的附加文件列表

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

仅适用于脚本/样式预处理器:要在标签上设置的更新属性。如果未定义,属性保持不变。

toString?: () => string;

警告

interface Warning extends ICompileDiagnostic {}

Edit this page on GitHub llms.txt