Svelte • Reference

svelte/compiler

On this page
import {
	compile,
	CompileError,
	compileModule,
	CompileOptions,
	CompileResult,
	MarkupPreprocessor,
	migrate,
	ModuleCompileOptions,
	parse,
	parseCss,
	preprocess,
	Preprocessor,
	PreprocessorGroup,
	print,
	Processed,
	VERSION,
	walk,
	Warning
} from 'svelte/compiler';

compile

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

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

compileModule

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

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

parse

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.

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

parseCss

The parseCss function parses a CSS stylesheet, returning its abstract syntax tree.

export function parseCss(source: string): AST.CSS.StyleSheetFile;

walk

Replace this with import { walk } from 'estree-walker'

export function walk(): never;

Processed

The result of a preprocessor run. If the preprocessor does not return a result, it is assumed that the code is unchanged.

export interface Processed {/*…*/}
code: string;

The new code

map?: string | object;

A source map mapping back to the original code

dependencies?: string[];

A list of additional files to watch for changes

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

Only for script/style preprocessors: The updated attributes to set on the tag. If undefined, attributes stay unchanged.

toString?: () => string;

MarkupPreprocessor

A markup preprocessor that takes a string of code and returns a processed version.

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

Preprocessor

A script/style preprocessor that takes a string of code and returns a processed version.

export 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

A preprocessor group is a set of preprocessors that are applied to a Svelte file.

export interface PreprocessorGroup {/*…*/}
name?: string;

Name of the preprocessor. Will be a required option in the next major version

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

CompileResult

The return value of compile from svelte/compiler

export interface CompileResult {/*…*/}
js: {
			/** The generated code */
			code: string;
			/** A source map */
			map: SourceMap;
		};

The compiled JavaScript

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

The compiled CSS

warnings: Warning[];

An array of warning objects that were generated during compilation. Each warning has several properties:

  • code is a string identifying the category of warning
  • message describes the issue in human-readable terms
  • start and end, if the warning relates to a specific location, are objects with line, column and character properties
metadata: {
			/**
			 * Whether the file was compiled in runes mode, either because of an explicit option or inferred from usage.
			 * For `compileModule`, this is always `true`
			 */
			runes: boolean;
		};

Metadata about the compiled component

ast: any;

The AST

Warning

export interface Warning extends ICompileDiagnostic {}

CompileError

export interface CompileError extends ICompileDiagnostic {}

CompileOptions

export interface CompileOptions extends ModuleCompileOptions {/*…*/}
name?: string;

Sets the name of the resulting JavaScript class (though the compiler will rename it if it would otherwise conflict with other variables in scope). If unspecified, will be inferred from filename

customElement?: boolean | ((options: { filename: string }) => boolean);

If true, tells the compiler to generate a custom element constructor instead of a regular Svelte component.

You can also pass a function that receives { filename } and returns a boolean.

accessors?: boolean;

If true, getters and setters will be created for the component's props. If false, they will only be created for readonly exported values (i.e. those declared with const, class and function). If compiling with customElement: true this option defaults to true.

namespace?: Namespace;

The namespace of the element; e.g., "html", "svg", "mathml".

immutable?: boolean;

If true, tells the compiler that you promise not to mutate any objects. This allows it to be less conservative about checking whether values have changed.

css?: 'injected' | 'external' | ((options: { filename: string }) => 'injected' | 'external');
  • 'injected': styles will be included in the head when using render(...), and injected into the document (if not already present) when the component mounts. For components compiled as custom elements, styles are injected to the shadow root.
  • 'external': the CSS will only be returned in the css field of the compilation result. Most Svelte bundler plugins will set this to 'external' and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable .css files. This is always 'injected' when compiling with customElement mode.

You can also pass a function that receives { filename } and returns either 'injected' or 'external'.

cssHash?: CssHashGetter;

A function that takes a { hash, css, name, filename } argument and returns the string that is used as a classname for scoped CSS. It defaults to returning svelte-${hash(filename ?? css)}.

preserveComments?: boolean;

If true, your HTML comments will be preserved in the output. By default, they are stripped out.

preserveWhitespace?: boolean;

If true, whitespace inside and between elements is kept as you typed it, rather than removed or collapsed to a single space where possible.

fragments?: 'html' | 'tree';

Which strategy to use when cloning DOM fragments:

runes?: boolean | undefined | ((options: { filename: string }) => boolean | undefined);

Set to true to force the compiler into runes mode, even if there are no indications of runes usage. Set to false to force the compiler into ignoring runes, even if there are indications of runes usage. Set to undefined (the default) to infer runes mode from the component code. Is always true for JS/TS modules compiled with Svelte. Will be true by default in Svelte 6. Note that setting this to true in your svelte.config.js will force runes mode for your entire project, including components in node_modules, which is likely not what you want. If you're using Vite, consider using dynamicCompileOptions instead.

discloseVersion?: boolean;

If true, exposes the Svelte major version in the browser by adding it to a Set stored in the global window.__svelte.v.

compatibility?: {
			/**
			 * Applies a transformation so that the default export of Svelte files can still be instantiated the same way as in Svelte 4 —
			 * as a class when compiling for the browser (as though using `createClassComponent(MyComponent, {...})` from `svelte/legacy`)
			 * or as an object with a `.render(...)` method when compiling for the server
			 * @default 5
			 */
			componentApi?: 4 | 5;
		};
sourcemap?: object | string;

An initial sourcemap that will be merged into the final output sourcemap. This is usually the preprocessor sourcemap.

outputFilename?: string;

Used for your JavaScript sourcemap.

cssOutputFilename?: string;

Used for your CSS sourcemap.

hmr?: boolean;

If true, compiles components with hot reloading support.

modernAst?: boolean;

If true, returns the modern version of the AST. Will become true by default in Svelte 6, and the option will be removed in Svelte 7.

ModuleCompileOptions

export interface ModuleCompileOptions {/*…*/}
dev?: boolean;

If true, causes extra code to be added that will perform runtime checks and provide debugging information during development.

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

If "client", Svelte emits code designed to run in the browser. If "server", Svelte emits code suitable for server-side rendering. If false, nothing is generated. Useful for tooling that is only interested in warnings.

filename?: string;

Used for debugging hints and sourcemaps. Your bundler plugin will set it automatically.

rootDir?: string;

Used for ensuring filenames don't leak filesystem information. Your bundler plugin will set it automatically.

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

A function that gets a Warning as an argument and returns a boolean. Use this to filter out warnings. Return true to keep the warning, false to discard it.

experimental?: {
			/**
			 * Allow `await` keyword in deriveds, template expressions, and the top level of components
			 * @since 5.36
			 */
			async?: boolean;
		};

Experimental options

preprocess

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.

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

print

print converts a Svelte AST node back into Svelte source code. It is primarily intended for tools that parse and transform components using the compiler’s modern AST representation.

print(ast) requires an AST node produced by parse with modern: true, or any sub-node within that modern AST. The result contains the generated source and a corresponding source map. The output is valid Svelte, but formatting details such as whitespace or quoting may differ from the original.

VERSION

The current version, as set in package.json.

export const VERSION: string;

migrate

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.

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