svelte/compiler
import {
const VERSION: stringThe current version, as set in package.json.
VERSION,
function compile(source: string, options: CompileOptions): CompileResultcompile converts your .svelte source code into a JavaScript module that exports a component
compile,
function compileModule(source: string, options: ModuleCompileOptions): CompileResultcompileModule takes your JavaScript source code containing runes, and turns it into a JavaScript module.
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 <style lang="sass"> block into vanilla CSS.
preprocess,
function walk(): neverwalk
} from 'svelte/compiler';版本
当前版本,如 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,则仅为只读导出值(即用 const、class 和 function 声明的值)创建它们。如果使用 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
将合并到最终输出源映射中的初始源映射。这通常是预处理器源映射。
outputFilename?: string;- 默认
null
用于您的 JavaScript 源映射。
cssOutputFilename?: string;- 默认
null
用于您的 CSS 源映射。
hmr?: boolean;- 默认
false
如果 true,则使用热重载支持编译组件。
modernAst?: boolean;- 默认
false
如果 true,则返回 AST 的现代版本。将在 Svelte 6 中默认为 true,并且该选项将在 Svelte 7 中删除。
CompileResult
svelte/compiler 中 compile 的返回值
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用人类可读的术语描述问题start和end(如果警告与特定位置相关)是具有line、column和character属性的对象
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;用于调试提示和源映射。您的捆绑器插件将自动设置它。
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;处理结果
预处理器运行的结果。如果预处理器没有返回结果,则假定代码未更改。
interface Processed {…}code: string;新的代码
map?: string | object;一个映射回原始代码的源映射
dependencies?: string[];需要监视更改的附加文件列表
attributes?: Record<string, string | boolean>;仅适用于脚本/样式预处理器:要设置在标签上的更新属性。如果未定义,则属性保持不变。
toString?: () => string;警告
interface Warning extends ICompileDiagnostic {}