new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Svelte · Language · all subjects

core/component-structure

84 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Svelte component file structure

A Svelte component file (.svelte) contains three sections: a script block for JavaScript, HTML markup in the template, and an optional style block for CSS scoped to the component.

<script module> for module-level logic

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. You can export bindings from this block as compiled module exports, but you cannot export default since the default export is the component itself.

<script module> Svelte 4 migration

In Svelte 4, the module-level script was created using <script context="module">. Svelte 5 uses the <script module> syntax instead.

TypeScript in <script> blocks

JavaScript in a <script> block can be replaced with TypeScript by adding the lang="ts" attribute to the script tag.

Module exports and TypeScript editor setup

When exporting bindings from a <script module> block and importing them into a .ts file, ensure your editor has proper TypeScript configuration. This is handled automatically by the Svelte VS Code extension and IntelliJ plugin, but other editors may require the typescript-svelte-plugin setup.

<script> block instance-level logic

The <script> block contains JavaScript or TypeScript (with lang="ts" attribute) that runs when a component instance is created. Variables declared or imported at the top level are accessible in the component's markup. This block can use runes to declare component props and add reactivity.

.svelte file structure overview

.svelte files are the foundation of Svelte applications. Each file contains three optional sections: a script block, markup, and a style block. All three sections are optional.

if block with else if clause

Multiple conditions can be evaluated sequentially using {:else if expression} between the opening {#if} and closing {/if} tags.

if block with else clause

An optional {:else} clause can be placed at the end of an if block to provide a fallback when no preceding conditions are true.

if block wrapping content types

Blocks in Svelte can wrap both elements and text content within elements. They are not limited to wrapping only full elements.

{#if} block syntax and structure

The {#if} block is used to conditionally render content in Svelte. The basic syntax is {#if expression}...{/if}. Conditions can be chained with {:else if expression} and optionally concluded with an {:else} clause. Blocks can wrap elements or text within elements.

{#key} with components

When {#key} is used around components, it causes them to be reinstantiated and reinitialised whenever the key expression changes.

Spread attributes syntax

Spread attributes allow many attributes or properties to be passed to an element or component at once using the `{...object}` syntax, such as `<Widget a="b" {...things} c="d" />`.

Lowercase tags denote HTML elements

A lowercase tag like `<div>` denotes a regular HTML element in a Svelte component.

Capitalized or dot notation tags denote components

A capitalized tag like `<Widget>` or a tag using dot notation like `<my.stuff>` indicates a Svelte component rather than an HTML element.

Attribute values can be unquoted

Attribute values may be unquoted in Svelte, just as in HTML. For example: `<input type=checkbox />`.

Attribute values can contain JavaScript expressions

Attribute values can contain JavaScript expressions interpolated with curly braces, such as `<a href="page/{p}">page {p}</a>`.

Attributes can be JavaScript expressions

Attributes can be assigned JavaScript expressions by using the format `attribute={expression}`, for example `<button disabled={!clickable}>...</button>`.

Boolean attributes inclusion rules

Boolean attributes are included on the element if their value is truthy and excluded if it is falsy.

Non-boolean attributes nullish handling

All non-boolean attributes are included on the element unless their value is nullish (null or undefined).

Shorthand for matching attribute name and value

When the attribute name and value match, such as `name={name}`, they can be replaced with the shorthand form `{name}`. For example, `<button {disabled}>` is equivalent to `<button disabled={disabled}>`.

Props terminology in Svelte

By convention, values passed to components are referred to as properties or props rather than attributes, which are a feature of the DOM.

HTML comments in Svelte components

HTML comments can be used inside Svelte components using standard HTML comment syntax: `<!-- this is a comment! -->`.

XSS prevention with @html tag

When using the `{@html}` tag, ensure the string is either escaped or only populated with values under your control to prevent XSS attacks.

@component comment for documentation

A special comment starting with `@component` can be added to a Svelte component. This comment will show up when hovering over the component name in other files. The comment supports markdown and code blocks for documentation purposes.

svelte-ignore comment for disabling warnings

Comments beginning with `svelte-ignore` disable warnings for the next block of markup. For example, `<!-- svelte-ignore a11y_autofocus -->` disables accessibility warnings.

@html tag for rendering HTML strings

To render HTML from a string expression, use the `{@html}` tag, such as `{@html potentiallyUnsafeHtmlString}`.

RegExp literals in templates require parentheses

If using a regular expression literal notation in a Svelte template, it must be wrapped in parentheses, such as `{(/^[A-Za-z ]+$/).test(value) ? x : y}`.

HTML entity strings for curly braces in templates

Curly braces can be included literally in a Svelte template by using HTML entity strings: `&lbrace;`, `&lcub;`, or `&#123;` for `{` and `&rbrace;`, `&rcub;`, or `&#125;` for `}`.

Null and undefined text expressions omitted

Text expressions that evaluate to `null` or `undefined` will be omitted from the rendered output. All other expressions are coerced to strings.

Text expressions with curly braces

A JavaScript expression can be included as text in a Svelte template by surrounding it with curly braces, such as `{expression}`.

Spread attributes order precedence

In spread attributes, order matters for precedence. If a property exists in the spread object, it takes precedence over a preceding attribute with the same name. Attributes following the spread take precedence over properties in the spread object. For example, in `<Widget a="b" {...things} c="d" />`, if `things.a` exists it overrides `a="b"`, while `c="d"` overrides `things.c`.

onMount lifecycle hook

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation but does not need to live inside the component; it can be called from an external module. onMount does not run inside a component that is rendered on the server. If a function is returned from onMount, it will be called when the component is unmounted. This cleanup behavior only works when the function passed to onMount is synchronous; async functions always return a Promise.

onDestroy lifecycle hook

The onDestroy function schedules a callback to run immediately before the component is unmounted. Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component.

tick function for UI updates

The tick function ensures that the UI is updated before continuing. It returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none. tick can be used when there is no 'after update' hook needed.

beforeUpdate and afterUpdate deprecated

In Svelte 5, beforeUpdate and afterUpdate are deprecated. These hooks were shimmed for backwards compatibility but are not available inside components that use runes. Instead of beforeUpdate, use $effect.pre. Instead of afterUpdate, use $effect. The runes offer more granular control and only react to the changes you're actually interested in.

Svelte 5 component lifecycle structure

In Svelte 5, the component lifecycle consists of only two parts: creation and destruction. Everything in-between when certain state is updated is not related to the component as a whole; only the parts that need to react to the state change are notified. The smallest unit of change is not a component but the render effects that the component sets up upon component initialization. There is no such thing as a 'before update'/'after update' hook.

SvelteHTMLElements for elements without dedicated types

For HTML elements without a dedicated type definition in svelte/elements, use SvelteHTMLElements: SvelteHTMLElements['div'] provides the type for a div element.

ComponentProps for extracting component properties

The ComponentProps type extracts the properties type from a component. Usage: ComponentProps<TComponent> where TComponent extends Component<any>.

Component type replaces SvelteComponent from Svelte 4

In Svelte 5, components are of type Component. In Svelte 4, components were of type SvelteComponent, which is now a legacy pattern.

Typing component instance with bind:this

To declare that a variable holds a component instance, use the component name as the type: let componentInstance: MyComponent. The instance is populated by bind:this on the component element: <MyComponent bind:this={componentInstance} />.

HTMLButtonAttributes for wrapper components

When writing a component that wraps a native element, use HTMLButtonAttributes (or similar for other elements) from svelte/elements to type and expose all underlying element attributes. Example: let { children, ...rest }: HTMLButtonAttributes = $props().

Component type for type constraints

The Component type from 'svelte' expresses constraints on components. Component<{ prop: string }> restricts dynamic components to those with at most the specified required properties.

Custom element lifecycle - Svelte component creation timing

When a custom element is created, the inner Svelte component is not created immediately. It is created in the next tick after the `connectedCallback` is invoked. Properties assigned before DOM insertion are temporarily saved and set on component creation, so their values are not lost.

Custom element destruction timing

The inner Svelte component is destroyed in the next tick after the `disconnectedCallback` is invoked.

SvelteComponentTyped deprecated in Svelte 4

SvelteComponentTyped is deprecated. SvelteComponent now has all its typing capabilities. Replace all instances of SvelteComponentTyped with SvelteComponent.

SvelteComponent generic typing in Svelte 4

If you previously used SvelteComponent as a component instance type with `: typeof SvelteComponent`, change it to `: typeof SvelteComponent<any>` to avoid type errors.

Components are dynamic by default in Svelte 5

In Svelte 5, <Thing /> is dynamic when Thing changes, unlike Svelte 4 where components were static. <svelte:component> is no longer necessary but still supported.

mount function replaces new Component() instantiation

In Svelte 5, components are no longer classes. Use mount() imported from 'svelte' to instantiate components. Example: const app = mount(App, { target: document.getElementById('app') });

hydrate function for server-rendered components

The hydrate function (imported from 'svelte') has the same API as mount but picks up server-rendered HTML inside its target and hydrates it.

mount and hydrate return component exports and accessors

mount and hydrate return an object with the exports of the component and, if compiled with accessors: true, property accessors. They do not return $on, $set, or $destroy methods.

unmount function replaces $destroy method

In Svelte 5, use unmount() imported from 'svelte' to destroy a component instance. Example: unmount(app);

events option on mount replaces $on method

To listen to component events when using mount, pass an events object with callbacks. Example: mount(App, { target: el, events: { event: callback } }); However, using callback props is recommended instead.

Create reactive state object for mount instead of $set

Instead of $set method, create a reactive state object using $state and pass it to mount as props. Then manipulate the state object directly. Example: const props = $state({ foo: 'bar' }); const app = mount(App, { target, props }); props.foo = 'baz';

createClassComponent available for backwards compatibility

The createClassComponent function (imported from 'svelte/legacy') provides backwards compatibility with the Svelte 4 class component API. It wraps functional components to provide $on, $set, and $destroy methods.

flushSync ensures onMount and pending blocks complete

mount and hydrate are not synchronous. Call flushSync (imported from 'svelte') after calling mount/hydrate to ensure onMount callbacks and pending blocks have executed.

render function for server-side rendering

In Svelte 5, use render (imported from 'svelte/server') to render components for server-side rendering. Example: const { html, head } = render(App, { props: { message: 'hello' } });

CSS is not returned from render by default

In Svelte 5, render does not return CSS by default unlike Svelte 4. If you need CSS, set the css compiler option to 'injected' to add <style> elements to the head.

Component type replaces SvelteComponent for typing

In Svelte 5, the Component type replaces SvelteComponent for type definitions. Example: import type { Component } from 'svelte'; export declare const MyComponent: Component<{ foo: string }>;

ComponentEvents and ComponentType types are deprecated

The ComponentEvents and ComponentType utility types are deprecated. ComponentEvents is obsolete because events are callback props now. ComponentType is obsolete because the Component type already serves that purpose.

Give your agent this brain