11 KiB
						
					
					
				
			
		
		
	
	| title | 
|---|
| Compile time | 
Typically, you won't interact with the Svelte compiler directly, but will instead integrate it into your build system using a bundler plugin:
- rollup-plugin-svelte for users of Rollup
- svelte-loader for users of webpack
- parcel-plugin-svelte for users of Parcel
Nonetheless, it's useful to understand how to use the compiler, since bundler plugins generally expose compiler options to you.
svelte.compile
result: {
	js,
	css,
	ast,
	warnings,
	vars,
	stats
} = svelte.compile(source: string, options?: {...})
This is where the magic happens. svelte.compile takes your component source code, and turns it into a JavaScript module that exports a class.
const svelte = require('svelte/compiler');
const result = svelte.compile(source, {
	// options
});
The following options can be passed to the compiler. None are required:
| option | default | description | 
|---|---|---|
| filename | null | stringused for debugging hints and sourcemaps. Your bundler plugin will set it automatically. | 
| name | "Component" | stringthat 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 fromfilename. | 
| format | "esm" | If "esm", creates a JavaScript module (withimportandexport). If"cjs", creates a CommonJS module (withrequireandmodule.exports), which is useful in some server-side rendering situations or for testing. | 
| generate | "dom" | If "dom", Svelte emits a JavaScript class for mounting to the DOM. If"ssr", Svelte emits an object with arendermethod suitable for server-side rendering. Iffalse, no JavaScript or CSS is returned; just metadata. | 
| dev | false | If true, causes extra code to be added to components that will perform runtime checks and provide debugging information during development. | 
| immutable | 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. | 
| hydratable | false | If true, enables thehydrate: trueruntime option, which allows a component to upgrade existing DOM rather than creating new DOM from scratch. | 
| legacy | false | If true, generates code that will work in IE9 and IE10, which don't support things likeelement.dataset. | 
| accessors | false | If true, getters and setters will be created for the component's props. Iffalse, they will only be created for readonly exported values (i.e. those declared withconst,classandfunction). If compiling withcustomElement: truethis option defaults totrue. | 
| customElement | false | If true, tells the compiler to generate a custom element constructor instead of a regular Svelte component. | 
| tag | null | A stringthat 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". | 
| css | true | If true, styles will be included in the JavaScript class and injected at runtime. It's recommended that you set this tofalseand use the CSS that is statically generated, as it will result in smaller JavaScript bundles and better performance. | 
| preserveComments | false | If true, your HTML comments will be preserved during server-side rendering. By default, they are stripped out. | 
| preserveWhitespace | false | If true, whitespace inside and between elements is kept as you typed it, rather than optimised by Svelte. | 
| outputFilename | null | A stringused for your JavaScript sourcemap. | 
| cssOutputFilename | null | A stringused for your CSS sourcemap. | 
| sveltePath | "svelte" | The location of the sveltepackage. Any imports fromsvelteorsvelte/[module]will be modified accordingly. | 
The returned result object contains the code for your component, along with useful bits of metadata.
const {
	js,
	css,
	ast,
	warnings,
	vars,
	stats
} = svelte.compile(source);
- jsand- cssare objects with the following properties:- codeis a JavaScript string
- mapis a sourcemap with additional- toString()and- toUrl()convenience methods
 
- astis an abstract syntax tree representing the structure of your component.
- warningsis an array of warning objects that were generated during compilation. Each warning has several properties:- codeis a string identifying the category of warning
- messagedescribes the issue in human-readable terms
- startand- end, if the warning relates to a specific location, are objects with- line,- columnand- characterproperties
- frame, if applicable, is a string highlighting the offending code with line numbers
 
- varsis an array of the component's declarations, used by eslint-plugin-svelte3 for example. Each variable has several properties:- nameis self-explanatory
- export_nameis the name the value is exported as, if it is exported (will match- nameunless you do- export...as)
- injectedis- trueif the declaration is injected by Svelte, rather than in the code you wrote
- moduleis- trueif the value is declared in a- context="module"script
- mutatedis- trueif the value's properties are assigned to inside the component
- reassignedis- trueif the value is reassigned inside the component
- referencedis- trueif the value is used outside the declaration
- writableis- trueif the value was declared with- letor- var(but not- const,- classor- function)
 
- statsis an object used by the Svelte developer team for diagnosing the compiler. Avoid relying on it to stay the same!
svelte.preprocess
result: {
	code: string,
	dependencies: Array<string>
} = svelte.preprocess(
	source: string,
	preprocessors: Array<{
		markup?: (input: { source: string, filename: string }) => Promise<{
			code: string,
			dependencies?: Array<string>
		}>,
		script?: (input: { source: string, attributes: Record<string, string>, filename: string }) => Promise<{
			code: string,
			dependencies?: Array<string>
		}>,
		style?: (input: { source: string, attributes: Record<string, string>, filename: string }) => Promise<{
			code: string,
			dependencies?: Array<string>
		}>
	}>,
	options?: {
		filename?: string
	}
)
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.
The first argument is the component source code. The second is an array of preprocessors (or a single preprocessor, if you only have one), where a preprocessor is an object with markup, script and style functions, each of which is optional.
Each markup, script or style function must return an object (or a Promise that resolves to an object) with a code property, representing the transformed source code, and an optional array of dependencies.
The markup function receives the entire component source text, along with the component's filename if it was specified in the third argument.
Preprocessor functions may additionally return a
mapobject alongsidecodeanddependencies, wheremapis a sourcemap representing the transformation. In current versions of Svelte it will be ignored, but future versions of Svelte may take account of preprocessor sourcemaps.
const svelte = require('svelte/compiler');
const { code } = svelte.preprocess(source, {
	markup: ({ content, filename }) => {
		return {
			code: content.replace(/foo/g, 'bar')
		};
	}
}, {
	filename: 'App.svelte'
});
The script and style functions receive the contents of <script> and <style> elements respectively. In addition to filename, they get an object of the element's attributes.
If a dependencies array is returned, it will be included in the result object. This is used by packages like rollup-plugin-svelte to watch additional files for changes, in the case where your <style> tag has an @import (for example).
const svelte = require('svelte/compiler');
const sass = require('node-sass');
const { dirname } = require('path');
const { code, dependencies } = svelte.preprocess(source, {
	style: async ({ content, attributes, filename }) => {
		// only process <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);
		}));
		return {
			code: css.toString(),
			dependencies: stats.includedFiles
		};
	}
}, {
	filename: 'App.svelte'
});
Multiple preprocessors can be used together. The output of the first becomes the input to the second. markup functions run first, then script and style.
const svelte = require('svelte/compiler');
const { code } = svelte.preprocess(source, [
	{
		markup: () => {
			console.log('this runs first');
		},
		script: () => {
			console.log('this runs third');
		},
		style: () => {
			console.log('this runs fifth');
		}
	},
	{
		markup: () => {
			console.log('this runs second');
		},
		script: () => {
			console.log('this runs fourth');
		},
		style: () => {
			console.log('this runs sixth');
		}
	}
], {
	filename: 'App.svelte'
});
svelte.VERSION
The current version, as set in package.json.
const svelte = require('svelte/compiler');
console.log(`running svelte version ${svelte.VERSION}`);