.svelte files
Components are the building blocks of Svelte applications. They are written into .svelte
files, using a superset of HTML.
All three sections — script, styles and markup — are optional.
<script module>
// module-level logic goes here
// (you will rarely use this)
</script>
<script>
// instance-level logic goes here
</script>
<!-- markup (zero or more items) goes here -->
<style>
/* styles go here */
</style>
<script>
A <script>
block contains JavaScript (or TypeScript, when adding the lang="ts"
attribute) that runs when a component instance is created. Variables declared (or imported) at the top level can be referenced in the component’s markup.
In addition to normal JavaScript, you can use runes to declare component props and add reactivity to your component. Runes are covered in the next section.
<script module>
A <script>
tag with a module
attribute runs once when the module first evaluates, rather than for each component instance. Variables declared in this block can be referenced elsewhere in the component, but not vice versa.
<script module>
let total = 0;
</script>
<script>
total += 1;
console.log(`instantiated ${total} times`);
</script>
You can export
bindings from this block, and they will become exports of the compiled module. You cannot export default
, since the default export is the component itself.
Legacy mode
In Svelte 4, this script tag was created using
<script context="module">
<style>
CSS inside a <style>
block will be scoped to that component.
<style>
p {
/* this will only affect <p> elements in this component */
color: burlywood;
}
</style>
For more information, head to the section on styling.