What is svelte?
Svelte is a modern JavaScript compiler that allows you to write high-performance user interfaces with significantly less boilerplate code than traditional frameworks. It shifts much of the work to compile time, producing highly optimized vanilla JavaScript at the end.
What are svelte's main functionalities?
Reactive Declarations
Svelte allows you to write reactive statements using the $: syntax. When the state changes, the reactive statements automatically update to reflect the new state.
let count = 0;
$: doubled = count * 2;
Component Definition
Components in Svelte are defined using a combination of HTML, CSS, and JavaScript, which are encapsulated within a single file with a .svelte extension.
<script>
export let name;
</script>
<h1>Hello {name}!</h1>
Store Management
Svelte provides a simple store mechanism to manage global state. The 'writable' store is a basic store that allows reading and writing values reactively.
import { writable } from 'svelte/store';
const count = writable(0);
Transitions and Animations
Svelte makes it easy to add transitions and animations to elements when they enter or leave the DOM.
import { fade } from 'svelte/transition';
<div in:fade={{ delay: 0, duration: 200 }}>Fade In</div>
Bindings
Svelte provides a concise syntax for two-way data binding to HTML elements, allowing for easy synchronization between the DOM and component state.
<script>
let value = '';
</script>
<input bind:value={value} />
Other packages similar to svelte
react
React is a popular JavaScript library for building user interfaces. It uses a virtual DOM for efficient updates, and it's known for its component-based architecture. Unlike Svelte, React requires a runtime library and often involves more boilerplate code.
vue
Vue is a progressive JavaScript framework used for building UIs and single-page applications. It is similar to Svelte in its component structure and reactivity model but differs in that it uses a virtual DOM and requires a runtime.
angular
Angular is a platform and framework for building single-page client applications using HTML and TypeScript. It is more prescriptive than Svelte, with a complex ecosystem and a steep learning curve, and it includes features like dependency injection and RxJS integration.
preact
Preact is a fast, 3kB alternative to React with the same modern API. It provides a similar component-based architecture but with a smaller footprint. Preact is closer to Svelte in terms of size but still operates with a virtual DOM.
Svelte
The magical disappearing UI framework.
Tooling
This is the Svelte compiler, which is primarily intended for authors of tooling that integrates Svelte with different build systems. If you just want to write Svelte components and use them in your app, you probably want one of those tools:
Build Systems
Additional tools
Example usage
import * as svelte from 'svelte';
const { js, css, ast } = svelte.compile(source, {
format: 'umd',
filename: 'MyComponent.html',
name: 'MyComponent',
amd: {
id: 'my-component'
},
onerror: err => {
console.error( err.message );
},
onwarn: warning => {
console.warn( warning.message );
}
});
API
The Svelte compiler exposes the following API:
compile(source [, options]) => { js, css, ast }
- Compile the component with the given options (see below). Returns an object containing the compiled JavaScript, a sourcemap, an AST and transformed CSS.create(source [, options]) => function
- Compile the component and return the component itself.preprocess(source, options) => Promise
— Preprocess a source file, e.g. to use PostCSS or CoffeeScriptVERSION
- The version of this copy of the Svelte compiler as a string, 'x.x.x'
.
Compiler options
The Svelte compiler optionally takes a second argument, an object of configuration options:
| Values | Description | Default |
---|
generate | 'dom' , 'ssr' , false | Whether to generate JavaScript code intended for use on the client ('dom' ), or for use in server-side rendering ('ssr' ). If false , component will be parsed and validated but no code will be emitted | 'dom' |
dev | true , false | Whether to enable run-time checks in the compiled component. These are helpful during development, but slow your component down. | false |
css | true , false | Whether to include code to inject your component's styles into the DOM. | true |
hydratable | true , false | Whether to support hydration on the compiled component. | false |
customElement | true , false , { tag, props } | Whether to compile this component to a custom element. If tag /props are passed, compiles to a custom element and overrides the values exported by the component. | false |
bind | boolean | If false , disallows bind: directives | true |
| | | |
shared | true , false , string | Whether to import various helpers from a shared external library. When you have a project with multiple components, this reduces the overall size of your JavaScript bundle, at the expense of having immediately-usable component. You can pass a string of the module path to use, or true will import from 'svelte/shared.js' . | false |
legacy | true , false | Ensures compatibility with very old browsers, at the cost of some extra code. | false |
| | | |
format | 'es' , 'amd' , 'cjs' , 'umd' , 'iife' , 'eval' | The format to output in the compiled component.
'es' - ES6/ES2015 module, suitable for consumption by a bundler
'amd' - AMD module
'cjs' - CommonJS module
'umd' - UMD module
'iife' - IIFE-wrapped function defining a global variable, suitable for use directly in browser
'eval' - standalone function, suitable for passing to eval() | 'es' for generate: 'dom'
'cjs' for generate: 'ssr' |
name | string | The name of the constructor in the compiled component. | 'SvelteComponent' |
filename | string | The filename to use in sourcemaps and compiler error and warning messages. | 'SvelteComponent.html' |
amd .id | string | The AMD module ID to use for the 'amd' and 'umd' output formats. | undefined |
globals | object , function | When outputting to the 'umd' , 'iife' or 'eval' formats, an object or function mapping the names of imported dependencies to the names of global variables. | {} |
preserveComments | boolean | Include comments in rendering. Currently, only applies to SSR rendering | false |
| | | |
onerror | function | Specify a callback for when Svelte encounters an error while compiling the component. Passed two arguments: the error object, and another function that is Svelte's default onerror handling. | (exception is thrown) |
onwarn | function | Specify a callback for when Svelte encounters a non-fatal warning while compiling the component. Passed two arguments: the warning object, and another function that is Svelte's default onwarn handling. | (warning is logged to console) |
Preprocessor options
svelte.preprocess
returns a Promise that resolves to an object with a toString
method (other properties will be added in future). It takes an options object with markup
, style
or script
properties:
const processed = await svelte.preprocess(source, {
markup: ({ content }) => {
return { code: '...', map: {...} };
},
style: ({ content, attributes }) => {
if (attributes.type !== 'text/scss') return;
return { code: '...', map: {...} };
},
script: ({ content, attributes }) => {
if (attributes.type !== 'text/coffeescript') return;
return { code: '...', map: {...} };
}
});
The style
and script
preprocessors will run after the markup
preprocessor. Each preprocessor can return a) nothing (in which case no transformation takes place), b) a { code, map }
object, or c) a Promise that resolves to a) or b). Note that sourcemaps are currently discarded, but will be used in future versions of Svelte.
Example/starter repos
BrowserStack
To keep Svelte's performance in check, we use BrowserStack to quickly run benchmarks for each PR that immediately give feedback to the contributor. You can see how we use BrowserStack in the svelte-bench project and check out BrowserStack's services on their website.
License
MIT