Skip to main content

Compilateur et API

svelte/compiler

Modifier cette page sur Github

En général, vous n'interagirez pas directement avec le compilateur Svelte, mais vous l'intègrerez plutôt dans un processus de build à travers un plugin de bundler. Le plugin que l'équipe Svelte recommande et avec lequel elle travaille est vite-plugin-svelte. Le framework SvelteKit fournit une configuration de vite-plugin-svelte qui permet de compiler des applications et de packager des librairies de composants Svelte. Svelte Society maintient des plugins pour d'autres bundlers (notamment Rollup et Webpack).

Néanmoins, il est utile de comprendre comment utiliser le compilateur, puisque les plugins exposent généralement des options.

compile

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

C'est ici que la magie opère. svelte.compile convertit le code source des composants en module JavaScript qui exporte des classes.

ts
import { compile } from 'svelte/compiler';
const result = compile(source, {
// options
});

Référez-vous à la section CompilerOptions pour voir les options disponibles.

L'objet retourné result contient le code du composant, ainsi que des métadonnées utiles.

ts
const { js, css, ast, warnings, vars, stats } = compile(source);

Référez-vous à la section CompilerResult pour une description du résultat compilé.

parse

ts
function parse(
template: string,
options?: ParserOptions
): Ast;

La méthode parse convertit un composant pour retourner son arbre de la syntaxe abstraite (AST). Contrairement à la compilation avec l'option generate: false, aucune validation ni analyse n'est effectuée. Notez que l'AST n'est pas considéré comme une API publique ; des changements critiques pourraient survenir à n'importe quel moment.

ts
import { parse } from 'svelte/compiler';
const ast = parse(source, { filename: 'App.svelte' });

preprocess

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

Un certain nombre de plugins de pré-processeur maintenus par la communauté est disponible pour vous permettre d'utiliser Svelte avec des outils comme TypeScript, PostCSS, SCSS, et Less.

Vous pouvez écrire votre propre pré-processeur en utilisant l'API `svelte.

La fonction preprocess fournit des framework pour transformer le code source d'un composant selon vos besoins. Par exemple, elle peut convertir un bloc <style lang="sass"> en css natif.

Le premier argument est le code source du composant lui-même. Le second argument est un tableau de pré-processeurs (ou éventuellement un seul pré-processeur si vous n'en avez qu'un). Un pré-processeur est un objet contenant trois fonctions : markup, script et style, toutes optionnelles.

La fonction markup reçoit en argument le markup du composant, et le nom du composant filename s'il était spécifié comme troisième argument.

Les fonctions script et style reçoivent le contenu des blocs <script> et <style> respectivement (content) ainsi que toute la source textuelle (markup) du composant. En plus du nom du fichier filename, elles reçoivent un objet contenant les attributs de l'élément.

Chaque fonction markup, script et style doit retourner un objet (ou une Promesse qui résout un objet) contenant un attribut code, représentant le code source transformé. Ces fonctions peuvent aussi renvoyer un tableau facultatif de dépendances dependencies qui représente les fichiers dont les changements sont à surveiller, ainsi qu'un objet map qui est une sourcemap renvoyant la transformation vers le code d'origine. Les pré-processeurs script et style peuvent de manière optionnelle renvoyer un ensemble d'attributs qui représentent les attributs mis à jour sur les balises <script>/<style>.

Les fonctions de preprocessing doivent également retourner un objet map en plus de code et dependencies, où map correspond à la sourcemap de la transformation.

ts
import { preprocess } from 'svelte/compiler';
import MagicString from 'magic-string';
const { code } = await preprocess(
source,
{
markup: ({ content, filename }) => {
const pos = content.indexOf('foo');
if (pos < 0) {
return { code: content };
}
const s = new MagicString(content, { filename });
s.overwrite(pos, pos + 3, 'bar', { storeName: true });
return {
code: s.toString(),
map: s.generateMap()
};
}
},
{
filename: 'App.svelte'
}
);

Si un tableau de dépendances dependencies est retourné, il sera inclus dans l'objet retourné. Ce tableau est utilisé par des librairies comme rollup-plugin-svelte pour surveiller les changements dans les fichiers, par exemple si un bloc <style> contient un import de type @import.

preprocess-sass.js
ts
import { preprocess } from 'svelte/compiler';
import MagicString from 'magic-string';
import sass from 'sass';
import { dirname } from 'path';
const { code } = await preprocess(
source,
{
name: 'my-fancy-preprocessor',
markup: ({ content, filename }) => {
// renvoie le code tel quel quand aucune string foo n'est présente
const pos = content.indexOf('foo');
if (pos < 0) {
return;
}
// Remplace foo par bar en utilisant MagicString qui fournit
// une sourcemap en plus du code modifié
const s = new MagicString(content, { filename });
s.overwrite(pos, pos + 3, 'bar', { storeName: true });
Property 'css' does not exist on type 'unknown'.
Property 'stats' does not exist on type 'unknown'.
2339
2339
Property 'css' does not exist on type 'unknown'.
Property 'stats' does not exist on type 'unknown'.
return {
code: s.toString(),
map: s.generateMap({ hires: true, file: filename })
};
Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.2345Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
},
style: async ({ content, attributes, filename }) => {
// traite uniquement <style lang="sass">
if (attributes.lang !== 'sass') return;
const { css, stats } = await new Promise((resolve, reject) =>
sass.render(
{
file: filename,
data: content,
includePaths: [dirname(filename)]
},
(err, result) => {
if (err) reject(err);
else resolve(result);
}
)
);
// supprime l'attribut lang de la balise <style>
delete attributes.lang;
return {
code: css.toString(),
dependencies: stats.includedFiles,
attributes
};
}
},
{
filename: 'App.svelte'
}
);

Plusieurs pré-processeurs peuvent être utilisés ensemble. La sortie du premier devient l'argument du second. Les fonctions sont exécutées dans l'ordre suivant : markup, script puis style.

En Svelte 3, toutes les fonctions markup étaient exécutées en premier, puis toutes les fonctions script et enfin toutes les fonctions style. Cet ordre a été changé dans Svelte 4.

multiple-preprocessor.js
ts
import { preprocess } from 'svelte/compiler';
const { code } = await preprocess(source, [
{
name: 'premier pré-processeur',
markup: () => {
console.log('ceci est éxécuté en premier');
},
script: () => {
console.log('ça en second');
},
style: () => {
console.log('ça en troisième');
}
},
{
name: 'second pré-processeur',
markup: () => {
console.log('ça en quatrième');
},
script: () => {
console.log('ça en cinquième');
},
style: () => {
console.log('ça en sixième');
}
}
], {
filename: 'App.svelte'
});
multiple-preprocessor.ts
ts
import { preprocess } from 'svelte/compiler';
const { code } = await preprocess(
source,
[
{
name: 'premier pré-processeur',
markup: () => {
console.log('ceci est éxécuté en premier');
},
script: () => {
console.log('ça en second');
},
style: () => {
console.log('ça en troisième');
},
},
{
name: 'second pré-processeur',
markup: () => {
console.log('ça en quatrième');
},
script: () => {
console.log('ça en cinquième');
},
style: () => {
console.log('ça en sixième');
},
},
],
{
filename: 'App.svelte',
},
);

walk

La fonction walk fournit un un moyen de parcourir les arbres AST générés par le parser, en utilisant l'utilitaire estree-walker du compilateur.

La fonction prend comme argument l'arbre AST à traiter et un objet contenant 2 méthodes facultatives : enter et leave. enter est appelée pour chaque noeud (si la méthode est définie). Puis, à moins que this.skip() n'ait été appelée lors de l'exécution de enter, chaque enfant est également traversé. Enfin, la méthode leave est appelée pour le noeud actuel.

compiler-walk.js
ts
import { walk } from 'svelte/compiler';
walk(ast, {
enter(node, parent, prop, index) {
faire_quelque_chose(node);
if (doit_ignorer_les_enfants(node)) {
this.skip();
}
},
leave(node, parent, prop, index) {
faire_autre_chose(node);
}
});
compiler-walk.ts
ts
import { walk } from 'svelte/compiler';
walk(ast, {
enter(node, parent, prop, index) {
faire_quelque_chose(node);
if (doit_ignorer_les_enfants(node)) {
this.skip();
}
},
leave(node, parent, prop, index) {
faire_autre_chose(node);
},
});

VERSION

ts
const VERSION: string;

La version actuelle, définie dans le fichier package.json.

ts
import { VERSION } from 'svelte/compiler';
console.log(`la version ${VERSION} de Svelte est en cours d'exécution`);

Types

CompileOptions

ts
interface CompileOptions {}
ts
name?: string;
  • default 'Component'

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

ts
filename?: string;
  • default null

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

ts
generate?: 'dom' | 'ssr' | false;
  • default 'dom'

If "dom", Svelte emits a JavaScript class for mounting to the DOM. If "ssr", Svelte emits an object with a render method suitable for server-side rendering. If false, no JavaScript or CSS is returned; just metadata.

ts
errorMode?: 'throw' | 'warn';
  • default 'throw'

If "throw", Svelte throws when a compilation error occurred. If "warn", Svelte will treat errors as warnings and add them to the warning report.

ts
varsReport?: 'full' | 'strict' | false;
  • default 'strict'

If "strict", Svelte returns a variables report with only variables that are not globals nor internals. If "full", Svelte returns a variables report with all detected variables. If false, no variables report is returned.

ts
sourcemap?: object | string;
  • default null

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

ts
enableSourcemap?: EnableSourcemap;
  • default true

If true, Svelte generate sourcemaps for components. Use an object with js or css for more granular control of sourcemap generation.

ts
outputFilename?: string;
  • default null

Used for your JavaScript sourcemap.

ts
cssOutputFilename?: string;
  • default null

Used for your CSS sourcemap.

ts
sveltePath?: string;
  • default 'svelte'

The location of the svelte package. Any imports from svelte or svelte/[module] will be modified accordingly.

ts
dev?: boolean;
  • default false

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

ts
accessors?: boolean;
  • default false

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.

ts
immutable?: boolean;
  • default false

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.

ts
hydratable?: boolean;
  • default false

If true when generating DOM code, enables the hydrate: true runtime option, which allows a component to upgrade existing DOM rather than creating new DOM from scratch. When generating SSR code, this adds markers to <head> elements so that hydration knows which to replace.

ts
legacy?: boolean;
  • default false

If true, generates code that will work in IE9 and IE10, which don't support things like element.dataset.

ts
customElement?: boolean;
  • default false

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

ts
tag?: string;
  • default null

A string that tells Svelte what tag name to register the custom element with. It must be a lowercase alphanumeric string with at least one hyphen, e.g. "my-element".

ts
css?: 'injected' | 'external' | 'none' | boolean;
  • 'injected' (formerly true), styles will be included in the JavaScript class and injected at runtime for the components actually rendered.
  • 'external' (formerly false), the CSS will 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.
  • 'none', styles are completely avoided and no CSS output is generated.
ts
loopGuardTimeout?: number;
  • default 0

A number that tells Svelte to break the loop if it blocks the thread for more than loopGuardTimeout ms. This is useful to prevent infinite loops. Only available when dev: true.

ts
namespace?: string;
  • default 'html'

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

ts
cssHash?: CssHashGetter;
  • default undefined

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(css)}.

ts
preserveComments?: boolean;
  • default false

If true, your HTML comments will be preserved during server-side rendering. By default, they are stripped out.

ts
preserveWhitespace?: boolean;
  • default false

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

ts
discloseVersion?: boolean;
  • default true

If true, exposes the Svelte major version on the global window object in the browser.

CompileResult

The returned shape of compile from svelte/compiler

ts
interface CompileResult {}
ts
js: {}

The resulting JavaScript code from compling the component

ts
code: string;

Code as a string

ts
map: any;

A source map

ts
css: CssResult;

The resulting CSS code from compling the component

ts
ast: Ast;

The abstract syntax tree representing the structure of the component

ts
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
  • frame, if applicable, is a string highlighting the offending code with line numbers
ts
vars: Var[];

An array of the component's declarations used by tooling in the ecosystem (like our ESLint plugin) to infer more information

ts
stats: {
timings: {
total: number;
};
};

An object used by the Svelte developer team for diagnosing the compiler. Avoid relying on it to stay the same!

CssHashGetter

ts
type CssHashGetter = (args: {
name: string;
filename: string | undefined;
css: string;
hash: (input: string) => string;
}) => string;

EnableSourcemap

ts
type EnableSourcemap =
| boolean
| { js: boolean; css: boolean };

MarkupPreprocessor

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

ts
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.

ts
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.

ts
interface PreprocessorGroup {}
ts
name?: string;

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

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

Processed

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

ts
interface Processed {}
ts
code: string;

The new code

ts
map?: string | object;

A source map mapping back to the original code

ts
dependencies?: string[];

A list of additional files to watch for changes

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

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

ts
toString?: () => string;

SveltePreprocessor

Utility type to extract the type of a preprocessor from a preprocessor group

ts
interface SveltePreprocessor<
PreprocessorType extends keyof PreprocessorGroup,
Options = any
> {}
ts
(options?: Options): Required<Pick<PreprocessorGroup, PreprocessorType>>;