` 内のすべてをターゲットにします: ```svelte ``` # {@attach ...} Attachments are functions that run in an [effect]($effect) when an element is mounted to the DOM or when [state]($state) read inside the function updates. Optionally, they can return a function that is called before the attachment re-runs, or after the element is later removed from the DOM. > [!NOTE] > Attachments are available in Svelte 5.29 and newer. ```svelte ... ``` An element can have any number of attachments. ## Attachment factories A useful pattern is for a function, such as `tooltip` in this example, to _return_ an attachment ([demo](/playground/untitled#H4sIAAAAAAAAE3VT0XLaMBD8lavbDiaNCUlbHhTItG_5h5AH2T5ArdBppDOEMv73SkbGJGnH47F9t3un3TsfMyO3mInsh2SW1Sa7zlZKo8_E0zHjg42pGAjxBPxp7cTvUHOMldLjv-IVGUbDoUw295VTlh-WZslqa8kxsLL2ACtHWxh175NffnQfAAGikSGxYQGfPEvGfPSIWtOH0TiBVo2pWJEBJtKhQp4YYzjG9JIdcuMM5IZqHMPioY8vOSA997zQoevf4a7heO7cdp34olRiTGr07OhwH1IdoO2A7dLMbwahZq6MbRhKZWqxk7rBxTGVbuHmhCgb5qDgmIx_J6XtHHukHTrYYqx_YpzYng8aO4RYayql7hU-1ZJl0akqHBE_D9KLolwL-Dibzc7iSln9XjtqTF1UpMkJ2EmXR-BgQErsN4pxIJKr0RVO1qrxAqaTO4fbc9bKulZm3cfDY3aZDgvFGErWjmzhN7KmfX5rXyDeX8Pt1mU-hXjdBOrtuB97vK4GPUtmJ41XcRMEGDLD8do0nJ73zhUhSlyRw0t3vPqD8cjfLs-axiFgNBrkUd9Ulp50c-GLxlXAVlJX-ffpZyiSn7H0eLCUySZQcQdXlxj4El0Yv_FZvIKElqqGTruVLhzu7VRKCh22_5toOyxsWqLwwzK-cCbYNdg-hy-p9D7sbiZWUnts_wLUOF3CJgQAAA==)): ```svelte Hover me ``` Since the `tooltip(content)` expression runs inside an [effect]($effect), the attachment will be destroyed and recreated whenever `content` changes. The same thing would happen for any state read _inside_ the attachment function when it first runs. (If this isn't what you want, see [Controlling when attachments re-run](#Controlling-when-attachments-re-run).) ## Inline attachments Attachments can also be created inline ([demo](/playground/untitled#H4sIAAAAAAAAE71Wf3OaWBT9KoyTTnW3MS-I3dYmnWXVtnRAazRJzbozRSQEApiRhwKO333vuY8m225m_9yZGOT9OPfcc84D943UTfxGr_G7K6Xr3TVeNW7D2M8avT_3DVk-YAoDNF4vNB8e2tnWjyXGlm7mPzfurVPpp5JgGmeZtwkf5PtFupCxLzVvHa832rl2lElX-s2Xm2DZFNqp_hs-rZetd4v07ORpT3qmQHu7MF2td0BZp8k6z_xkvfXP902_pZ2_1_aYWEiqm0kN8I4r79qbdZ6umnq3q_2iNf22F4dE6qt2oimwdpim_uY6XMm7Fuo-IQT_iTD_CeGTHwZ38ieIJUFQRxirR1Xf39Dw0X5z0I72Af4tD61vvPNwWKQnqmfPTbduhsEd2J3vO_oBd3dc6fF2X7umNdWGf0vBRhSS6qoV7cCXfTXWfKmvWG61_si_vfU92Wz-E4RhsLhNIYinsox9QKGVd8-tuACCeKXRX12P-T_eKf7fhTq0Hvt-f3ailtSeoxJHRo1-58NoPe1UiBc1hkL8Yeh45y_vQ3mcuNl9T8s3cXPRWLnS7YWJG_gn2Tb4tUjid8jua-PVl08j_ab8I14mH8Llx0s5Tz5Err4ql52r_GYg0mVy1bEGZuD0ze64b5TWYFiM-16wSuJ4JT5vfVpDcztrcG_YkRU4s6HxufzDWF4XuVeJ1P10IbzBemt3Vp1V2e04ZXfrJd7Wicyd039brRIv_RIVu_nXi7X1cfL2sy66ztToUp1TO7qJ7NlwZ0f30pld5qNSVE5o6PbMojFHjgZB7oSicPpGteyLclQap7SvY0dXtM_LR1NT2JFHey3aaxa0VxCeYJ7RMHemoiCcgPZV9pR7o7kgcOjeGliYk9hjDZx8FAq6enwlTPSZj_vYPw9Il64dXdIY8ZmapzwfEd8-1ZyaxWhqkIZOibXUd-6Upqi1pD4uMicCV1GA_7zi73UN8BaF4sC8peJtMjfmjbHZBFwq5ov50qRaE0l96NZggnW4KqypYRAW-uhSz9ADvklwJF2J-5W0Z5fQPBhDX92R6I_0IFxRgDftge4l4dP-gH1hjD7uqU6fsOEZ9UNrCdPB-nys6uXgY6O3ZMd9sy5T9PghqrWHdjo4jB51CgLiKJaDYYA-7WgYONf1FbjkI-mE3EAfUY_rijfuJ_CVPaR50oe9JF7Q0pI8Dw3osxxYHdYPGbp2CnwHF8KvwJv2wEv0Z3ilQI6U9uwbZxbYJXvEmjjQjjCHkvNLvNg3yhzXQd1olamsT4IRrZmX0MUDpwL7R8zzHj7pSh9hPHFSHjLezKqAST51uC5zmtQ87skDUaneLokT5RbXkPWSYz53Abgjc8_o4KFGUZ-Hgv2Z1l5OTYM9D-HfUD0L-EwxH5wRnIG61gS-khfgY1bq7IAP_DA4l5xRuh9xlm8yGjutc8t-wHtkhWv3hc7aqGwiK5KzgvM5xRkZYn193uEln-su55j1GaIv7oM4iPrsVHiG0Dx7TR9-1lBfqFdwfvSd5LNL5xyZVp5NoHFZ57FkfiF6vKs4k5zvIfrX5xX6MXmt0gM5MTu8DjnhukrHHzTRd3jm0dma0_f_x5cxP9f4jBdqHvmbq2fUjzqcKh2Cp-yWj9ntcHanXmBXxhu7Q--eyjhfNFpaV7zgz4nWEUb7zUOhpevjjf_gu_KZ99pxFlZ-T3sttkmYqrco_26q35v0Ewzv5EZPbnL_8BfduWGMnyyN3q0bZ_7hb_7KG_L4CQAA)): ```svelte { const context = canvas.getContext('2d'); $effect(() => { context.fillStyle = color; context.fillRect(0, 0, canvas.width, canvas.height); }); }} > ``` > [!NOTE] > The nested effect runs whenever `color` changes, while the outer effect (where `canvas.getContext(...)` is called) only runs once, since it doesn't read any reactive state. ## Passing attachments to components When used on a component, `{@attach ...}` will create a prop whose key is a [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol). If the component then [spreads](/tutorial/svelte/spread-props) props onto an element, the element will receive those attachments. This allows you to create _wrapper components_ that augment elements ([demo](/playground/untitled#H4sIAAAAAAAAE3VUS3ObMBD-KxvajnFqsJM2PhA7TXrKob31FjITAbKtRkiMtDhJPfz3LiAMdpxhGJvdb1_fPnaeYjn3Iu-WIbJ04028lZDcetHDzsO3olbVApI74F1RhHbLJdayhFl-Sp5qhVwhufEWNjWiwJtYxSjyQhsEFEXxBiujcxg1_8O_dnQ9APwsEbVyiHDafjrvDZCgkiO4MLCEzxYZcn90z6XUZ6OxA61KlaIgV6i1pFC-sxjDrlbHaDiWRoGvdMbHsLzp5DES0mJnRxGaRBvcBHb7yFUTCQeunEWYcYtGv12TqgFUDbCK1WLaM6IWQhUlQiJUFm2ZLPly51xXMG0Rjoyd69C7UqqG2nu95QZyXvtvLVpri2-SN4hoLXXCZFfhQ8aQBU1VgdEaH_vSgyBZR_BpPp_vi0tY-rw2ulRZkGqpTQRbZvwa2BPgFC8bgbw31CbjJjAsE6WNYBZeGp7vtQXLMqHWnZx-5kM1TR5ycpkZXQR2wzL94l8Ur1C_3-g168SfQf1MyfRi3LW9fs77emJEw5QV9SREoLTq06tcczq7d6xEUcJX2vAhO1b843XK34e5unZEMBr15ekuKEusluWAF8lXhE2ZTP2r2RcIHJ-163FPKerCgYJLOB9i4GvNwviI5-gAQiFFBk3tBTOU3HFXEk0R8o86WvUD64aINhv5K3oRmpJXkw8uxMG6Hh6JY9X7OwGSqfUy9tDG3sHNoEi0d_d_fv9qndxRU0VClFqo3KVo3U655Hnt1PXB3Qra2Y2QGdEwgTAMCxopsoxOe6SD0gD8movDhT0LAnhqlE8gVCpLWnRoV7OJCkFAwEXitrYL1W7p7pbiE_P7XH6E_rihODm5s52XtiH9Ekaw0VgI9exadWL1uoEYjPtg2672k5szsxbKyWB2fdT0w5Y_0hcT8oXOlRetmLS8-g-6TLXXQgYAAA==)): ```svelte {@render children?.()} ``` ```svelte Hover me ``` ## Controlling when attachments re-run Attachments, unlike [actions](use), are fully reactive: `{@attach foo(bar)}` will re-run on changes to `foo` _or_ `bar` (or any state read inside `foo`): ```js // @errors: 7006 2304 2552 function foo(bar) { return (node) => { veryExpensiveSetupWork(node); update(node, bar); }; } ``` In the rare case that this is a problem (for example, if `foo` does expensive and unavoidable setup work) consider passing the data inside a function and reading it in a child effect: ```js // @errors: 7006 2304 2552 function foo(+++getBar+++) { return (node) => { veryExpensiveSetupWork(node); +++ $effect(() => { update(node, getBar()); });+++ } } ``` ## Creating attachments programmatically To add attachments to an object that will be spread onto a component or element, use [`createAttachmentKey`](svelte-attachments#createAttachmentKey). ## Converting actions to attachments If you're using a library that only provides actions, you can convert them to attachments with [`fromAction`](svelte-attachments#fromAction), allowing you to (for example) use them with components. # {@const ...} `{@const ...}` タグはローカル定数を定義します。 ```svelte {#each boxes as box} {@const area = box.width * box.height} {box.width} * {box.height} = {area} {/each} ``` `{@const}` は、`{#if ...}`、`{#each ...}`、`{#snippet ...}` などのブロックや、``、または `` の直下の子としてのみ使用可能です。 # {@debug ...} `{@debug ...}` タグは、`console.log(...)` の代替手段を提供します。このタグは、特定の変数の値が変更されるたびにその値をログ出力し、開発者ツールが開いている場合はコードの実行を一時停止します。 ```svelte {@debug user} Hello {user.firstname}! ``` `{@debug ...}` は、変数名をカンマ区切りで指定することができます (任意の式は指定できません)。 ```svelte {@debug user} {@debug user1, user2, user3} {@debug user.firstname} {@debug myArray[0]} {@debug !isReady} {@debug typeof user === 'object'} ``` 引数なしの `{@debug}` タグは、特定の変数ではなく、_何らかの_ state が変化した際にトリガーされる `debugger` ステートメントを挿入します。 # bind: データは通常、親から子へと流れますが、`bind:` ディレクティブを使用すると、データを子から親へ流すことができます。 一般的な構文は `bind:property={expression}` であり、`expression` は [_lvalue_](https://press.rebus.community/programmingfundamentals/chapter/lvalue-and-rvalue/) (つまり、変数やオブジェクトのプロパティ) です。式がプロパティと同じ名前の識別子である場合、式を省略することができます — 言い換えると、以下は等価です: ```svelte ``` Svelte は、バインドされた値を更新するイベントリスナーを作成します。要素が既に同じイベントのリスナーを持っている場合、そのリスナーはバインドされた値が更新される前に実行されます。 ほとんどのバインディングは _双方向_ であり、値の変更が要素に影響し、その逆も同様です。一部のバインディングは _読み取り専用_ であり、値を変更しても要素に影響を与えません。 ## Function bindings `bind:property={get, set}` を使用して、`get` と `set` を関数として指定し、バリデーションや変換を行うことができます: ```svelte value, (v) => value = v.toLowerCase()} /> ``` [dimension bindings](#Dimensions) のような読み取り専用バインディングの場合、`get` の値は `null` にする必要があります: ```svelte ... ``` > [!NOTE] > Function bindings は Svelte 5.9.0 以降で使用可能です。 ## `` `` 要素に対する `bind:value` ディレクティブは、input の `value` プロパティをバインドします: ```svelte {message} ``` 数値を扱う input (`type="number"` または `type="range"`) の場合、値は数値に変換されます ([デモ](/playground/untitled#H4sIAAAAAAAAE6WPwYoCMQxAfyWEPeyiOOqx2w74Hds9pBql0IllmhGXYf5dKqwiyILsLXnwwsuI-5i4oPkaUX8yo7kCnKNQV7dNzoty4qSVBSr8jG-Poixa0KAt2z5mbb14TaxA4OCtKCm_rz4-f2m403WltrlrYhMFTtcLNkoeFGqZ8yhDF7j3CCHKzpwoDexGmqCL4jwuPUJHZ-dxVcfmyYGe5MAv-La5pbxYFf5Z9Zf_UJXb-sEMquFgJJhBmGyTW5yj8lnRaD_w9D1dAKSSj7zqAQAA)): ```svelte {a} + {b} = {a + b} ``` 入力が空または無効 (`type="number"` の場合) の場合、値は `undefined` になります。 バージョン 5.6.0 以降、`` に `defaultValue` が設定されていてフォームの一部である場合、フォームがリセットされると空文字列ではなくその値に戻ります。初回のレンダリングでは、バインディングの値が `null` または `undefined` でない限り優先されることに注意してください。 ```svelte ``` > [!NOTE] > リセットボタンは慎重に使用し、ユーザーがフォームを送信しようとしているときに誤ってクリックしないようにしてください。 ## `` checkbox および radio の input には、`bind:checked` を使用してバインドできます: ```svelte Accept terms and conditions ``` バージョン 5.6.0 以降、`` に `defaultChecked` 属性が設定されておりフォームの一部である場合、フォームがリセットされると `false` ではなくその値に戻ります。初回のレンダリングでは、バインディングの値が `null` または `undefined` でない限り優先されます。 ```svelte ``` ## `` チェックボックスは、それがチェックされているかされていないかに関係なく、[indeterminate](https://developer.mozilla.org/ja/docs/Web/API/HTMLInputElement/indeterminate) 状態にすることができます: ```svelte {#if indeterminate} waiting... {:else if checked} checked {:else} unchecked {/if} ``` ## `` 相互に動作する input は、`bind:group` を使用できます。 ([demo](/playground/untitled#H4sIAAAAAAAAE62T32_TMBDH_5XDQkpbrct7SCMGEvCEECDxsO7BSW6L2c227EvbKOv_jp0f6jYhQKJv5_P3PvdL1wstH1Bk4hMSGdgbRzUssFaM9VJciFtF6EV23QvubNRFR_BPUVfWXvodEkdfKT3-zl8Zzag5YETuK6csF1u9ZUIGNo4VkYQNvPYsGRfJF5JKJ8s3QRJE6WoFb2Nq6K-ck13u2Sl9Vxxhlc6QUBIFnz9Brm9ifJ6esun81XoNd860FmtwslYGlLYte5AO4aHlVhJ1gIeKWq92COt1iMtJlkhFPkgh1rHZiiF6K6BUus4G5KafGznCTlIbVUMfQZUWMJh5OrL-C_qjMYSwb1DyiH7iOEuCb1ZpWTUjfHqcwC_GWDVY3ZfmME_SGttSmD9IHaYatvWHIc6xLyqad3mq6KuqcCwnWn9p8p-p71BqP2IH81zc9w2in-od7XORP7ayCpd5YCeXI_-p59mObPF9WmwGpx3nqS2Gzw8TO3zOaS5_GqUXyQUkS3h8hOSz0ZhMESHGc0c4Hm3MAn00t1wrb0l2GZRkqvt4sXwczm6Qh8vnUJzI2LV4vAkvqWgfehTZrSSPx19WiVfFfAQAAA==)): ```svelte Plain Whole wheat Spinach Rice Beans Cheese Guac (extra) ``` > [!NOTE] `bind:group` は、input が同じ Svelte コンポーネント内にある場合にのみ機能します。 ## `` `type="file"` を持つ `` 要素では、`bind:files` を使用して [選択されたファイルの `FileList`](https://developer.mozilla.org/ja/docs/Web/API/FileList) を取得できます。プログラムでファイルを更新する場合、常に `FileList` オブジェクトを使用する必要があります。現在、`FileList` オブジェクトは直接作成できないため、新しい [`DataTransfer`](https://developer.mozilla.org/ja/docs/Web/API/DataTransfer) オブジェクトを作成し、そこから `files` を取得する必要があります。 ```svelte Upload a picture: clear ``` `FileList` オブジェクトも変更できないため、例えばリストから単一のファイルを削除したい場合は、新しい `DataTransfer` オブジェクトを作成し、保持したいファイルを追加する必要があります。 > [!NOTE] `DataTransfer` はサーバーサイドの JS ランタイムでは利用できない場合があります。`files` にバインドされた state を未初期化のままにしておくことで、コンポーネントがサーバーサイドレンダリングされる際の潜在的なエラーを防ぐことができます。 ## `` `` の値のバインディングは、選択された `` の `value` プロパティに対応しており、これは通常の DOM での場合と異なり、文字列だけでなく任意の値を使用できます。 ```svelte a b c ``` `` 要素は、チェックボックスグループと同様に動作します。バインドされた変数は、選択された各 `` の `value` プロパティに対応するエントリを持つ配列です。 ```svelte Rice Beans Cheese Guac (extra) ``` `` の値がそのテキストコンテンツと一致する場合、その属性は省略できます。 ```svelte Rice Beans Cheese Guac (extra) ``` `` にデフォルト値を設定するには、初期選択すべき `` (または `` の場合は複数の ``) に `selected` 属性を追加します。`` がフォームの一部である場合、フォームがリセットされるとその選択に戻ります。初回レンダリング時には、バインディングの値が `undefined` でない限り優先されます。 ```svelte a b c ``` ## `` `` 要素には、以下の5つの双方向バインディングがあります: - [`currentTime`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/currentTime) - [`playbackRate`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/playbackRate) - [`paused`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/paused) - [`volume`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/volume) - [`muted`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/muted) ...および以下の6つの読み取り専用バインディングがあります: - [`duration`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/duration) - [`buffered`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/buffered) - [`seekable`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/seekable) - [`seeking`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/seeking_event) - [`ended`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/ended) - [`readyState`](https://developer.mozilla.org/ja/docs/Web/API/HTMLMediaElement/readyState) - [`played`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/played) ```svelte ``` ## `` `` 要素には、[``](#audio) 要素と同じバインディングがすべて含まれ、さらに読み取り専用の [`videoWidth`](https://developer.mozilla.org/ja/docs/Web/API/HTMLVideoElement/videoWidth) および [`videoHeight`](https://developer.mozilla.org/ja/docs/Web/API/HTMLVideoElement/videoHeight) バインディングがあります。 ## `` `` 要素には、以下の2つの読み取り専用バインディングがあります: - [`naturalWidth`](https://developer.mozilla.org/ja/docs/Web/API/HTMLImageElement/naturalWidth) - [`naturalHeight`](https://developer.mozilla.org/ja/docs/Web/API/HTMLImageElement/naturalHeight) ## `` `` 要素は、`open` プロパティへのバインディングをサポートします。 ```svelte How do you comfort a JavaScript bug? You console it. ``` ## `window` and `document` To bind to properties of `window` and `document`, see [``](svelte-window) and [``](svelte-document). ## Contenteditable bindings `contenteditable` 属性を持つ要素は、以下のバインディングをサポートします: - [`innerHTML`](https://developer.mozilla.org/ja/docs/Web/API/Element/innerHTML) - [`innerText`](https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/innerText) - [`textContent`](https://developer.mozilla.org/ja/docs/Web/API/Node/textContent) > [!NOTE] [`innerText` と `textContent` には微妙な違いがあります](https://developer.mozilla.org/ja/docs/Web/API/Node/textContent#innertext_との違い)。 ```svelte ``` ## Dimensions すべての visible な要素には、以下の読み取り専用バインディングがあり、これらは `ResizeObserver` を使用して測定されます: - [`clientWidth`](https://developer.mozilla.org/ja/docs/Web/API/Element/clientWidth) - [`clientHeight`](https://developer.mozilla.org/ja/docs/Web/API/Element/clientHeight) - [`offsetWidth`](https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/offsetWidth) - [`offsetHeight`](https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/offsetHeight) - [`contentRect`](https://developer.mozilla.org/ja/docs/Web/API/ResizeObserverEntry/contentRect) - [`contentBoxSize`](https://developer.mozilla.org/ja/docs/Web/API/ResizeObserverEntry/contentBoxSize) - [`borderBoxSize`](https://developer.mozilla.org/ja/docs/Web/API/ResizeObserverEntry/borderBoxSize) - [`devicePixelContentBoxSize`](https://developer.mozilla.org/ja/docs/Web/API/ResizeObserverEntry/devicePixelContentBoxSize) ```svelte ``` > [!NOTE] `display: inline` 要素には width や height がありません (`` や `` のような「固有の」 dimension を持つ要素を除く)。そのため、`ResizeObserver` で観測することはできません。これらの要素の `display` スタイルを `inline-block` などに変更する必要があります。CSS transformation は `ResizeObserver` コールバックをトリガーしないことにご注意ください。 ## bind:this ```svelte bind:this={dom_node} ``` DOM ノードへの参照を取得するには、`bind:this` を使用します。この値はコンポーネントがマウントされるまで `undefined` のままです — 言い換えると、初期化時ではなく、effect やイベントハンドラー内で読み取る必要があります: ```svelte ``` コンポーネントも `bind:this` をサポートしており、プログラムでコンポーネントインスタンスを操作できます。 ```svelte cart.empty()}> Empty shopping cart ``` ```svelte ``` ## bind:_property_ for components ```svelte bind:property={variable} ``` 要素と同じ構文を使用して、コンポーネントの props にバインドできます。 ```svelte ``` Svelte の props はバインディングなしでもリアクティブですが、そのリアクティビティはデフォルトでコンポーネント内にのみ流れます。`bind:property` を使用すると、コンポーネント内から props の変更をコンポーネント外に流すことができます。 props がバインド可能なものとしてマークするには、[`$bindable`]($bindable) rune を使用します: ```svelte ``` props をバインド可能として宣言することは、それが `bind:` を使用できることを意味しますが、`bind:` を使用しなければならないことを意味するわけではありません。 bindable な props にはフォールバック値を設定できます: ```svelte ``` このフォールバック値は、props がバインドされていない場合にのみ適用されます。props がバインドされていてフォールバック値が存在する場合、親コンポーネントは `undefined` 以外の値を提供する必要があります。そうでない場合、ランタイムエラーが発生します。これにより、どの値が適用されるかが不明確な状況になるのを防ぎます。 # use: > [!NOTE] > Svelte 5.29 以上の場合、代わりに [attachments](@attach) の使用をご検討ください。よりフレキシブルでコンポーザブルです。 action は、要素がマウントされたときに呼び出される関数です。これらは `use:` ディレクティブを使用して追加され、通常は `$effect` を使用して、要素がアンマウントされたときに state をリセットします: ```svelte ... ``` action には引数を渡すことができます: ```svelte ... ``` action は一度だけ呼び出されます (サーバーサイドレンダリング時には呼び出されません) — 引数が変更されても再実行されることはありません。 > [!LEGACY] > `$effect` rune が導入される前は、action は `update` と `destroy` メソッドを持つオブジェクトを返すことができました。この場合、引数が変更されると `update` が最新の値で呼び出されました。現在は effect の使用が推奨されています。 ## 型付け `Action` インターフェースは、3つのオプションの型引数を受け取ります — ノードの型 (action がすべての要素に適用される場合は `Element` にできます)、パラメーター、および action によって作成されるカスタムイベントハンドラーです: ```svelte ... ``` # transition: _transition_ は、state の変化の結果として DOM に要素が出入りする際にトリガーされます。 ブロック (例えば `{#if ...}` ブロック) が外へ transition している間、その中のすべての要素 (独自の transition を持たないものも含む) は、ブロック内のすべての transition が完了するまで DOM に保持されます。 `transition:` ディレクティブは _双方向_ transition を示します。これにより、transition の進行中でもスムーズに反転させることができることを意味しています。 ```svelte visible = !visible}>toggle {#if visible} fades in and out {/if} ``` ## Local vs global transition はデフォルトで local です。local transition は、それが属するブロックが作成または破棄されるときにのみ実行され、親ブロックが作成または破棄されるときには実行されません。 ```svelte {#if x} {#if y} fades in and out only when y changes fades in and out when x or y change {/if} {/if} ``` ## Built-in transitions A selection of built-in transitions can be imported from the [`svelte/transition`](svelte-transition) module. ## Transition parameters transition にはパラメータを指定することができます。 (二重の `{{中括弧}}` は特別な構文ではありません。これは式タグ内のオブジェクトリテラルです。) ```svelte {#if visible} fades in and out over two seconds {/if} ``` ## Custom transition functions ```js /// copy: false // @noErrors transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => { delay?: number, duration?: number, easing?: (t: number) => number, css?: (t: number, u: number) => string, tick?: (t: number, u: number) => void } ``` transition にはカスタム関数を使用することができます。返されるオブジェクトに `css` 関数が含まれている場合、Svelte は [web animation](https://developer.mozilla.org/ja/docs/Web/API/Web_Animations_API) のキーフレームを生成します。 `css` に渡される `t` 引数は、`easing` 関数が適用された後の `0` から `1` の間の値です。_in_ transition は `0` から `1` に進行し、_out_ transition は `1` から `0` に進行します — 言い換えると、`1` は transition が適用されていない要素の自然な状態です。`u` 引数は `1 - t` に等しい値です。 この関数は、transition が開始される前に、異なる `t` および `u` 引数とともに繰り返し呼び出されます。 ```svelte {#if visible} whooshes in {/if} ``` カスタムの transition 関数は、transition の途中で同じ `t` と `u` の引数と共に呼び出される `tick` 関数を返すこともできます。 > [!NOTE] `tick` の代わりに `css` を使用できる場合は、そうしてください — web animation はメインスレッドの外で実行されるため、低速なデバイスでのカクつきを防ぐことができます。 ```svelte {#if visible} The quick brown fox jumps over the lazy dog {/if} ``` transition が transition オブジェクトの代わりに関数を返す場合、その関数は次のマイクロタスク内で呼び出されます。これにより、複数の transition が調整され、[クロスフェード効果](/tutorial/deferred-transitions) を実現できます。 transition 関数は、transition に関する情報を含む第3引数 `options` を受け取ります。 `options` オブジェクトで使用可能な値は以下の通りです: - `direction` - transition のタイプに応じて `in`、`out`、`both` のいずれか ## Transition events transition を持つ要素は、標準の DOM イベントに加えて次のイベントをディスパッチします: - `introstart` - `introend` - `outrostart` - `outroend` ```svelte {#if visible} (status = 'intro started')} onoutrostart={() => (status = 'outro started')} onintroend={() => (status = 'intro ended')} onoutroend={() => (status = 'outro ended')} > Flies in and out {/if} ``` # in: and out: `in:` ディレクティブと `out:` ディレクティブは [`transition:`](transition) と同じですが、`in:` と `out:` の場合は双方向でない点が異なります — transition の進行中にブロックが消される場合、`in` transition は反転するのでなく、`out` transition と一緒に再生され続けます。`out` transition が中止されると、transition は最初からやり直されます。 ```svelte visible {#if visible} flies in, fades out {/if} ``` # animate: [keyed each block](each#Keyed-each-blocks) のコンテンツが並べ替えられると、アニメーションがトリガーされます。アニメーションは要素が追加または削除されたときには実行されず、each ブロック内の既存データ項目のインデックスが変更された場合にのみ実行されます。animate ディレクティブは、keyed each ブロックの _直下_ にある要素に付ける必要があります。 アニメーションは、Svelte の [組み込みアニメーション関数](svelte-animate) または [カスタムアニメーション関数](#Custom-animation-functions) を使用して実現できます。 ```svelte {#each list as item, index (item)} {item} {/each} ``` ## Animation Parameters action や transition と同様に、アニメーションにもパラメータを設定することができます。 (二重の `{{curlies}}` は特別な構文ではありません。これは式タグ内のオブジェクトリテラルです。) ```svelte {#each list as item, index (item)} {item} {/each} ``` ## Custom animation functions ```js /// copy: false // @noErrors animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => { delay?: number, duration?: number, easing?: (t: number) => number, css?: (t: number, u: number) => string, tick?: (t: number, u: number) => void } ``` アニメーションには、`node`、`animation` オブジェクト、および任意の `parameters` を引数として提供するカスタム関数を使用することができます。`animation` パラメータは、要素の `start` と `end` の位置を記述した [DOMRect](https://developer.mozilla.org/en-US/docs/Web/API/DOMRect#Properties) を含む `from` および `to` プロパティを持つオブジェクトです。`from` プロパティは要素の開始位置を表す DOMRect で、`to` プロパティはリストが並べ替えられて DOM が更新された後の要素の最終位置を表す DOMRect です。 返されたオブジェクトに `css` メソッドがある場合、Svelte は要素上で再生される [web animation](https://developer.mozilla.org/ja/docs/Web/API/Web_Animations_API) を作成します。 `css` に渡される `t` 引数は、`easing` 関数が適用された後に `0` から `1` に変化する値です。`u` 引数は `1 - t` に等しい値です。 この関数は、アニメーションが開始する前に異なる `t` および `u` 引数で繰り返し呼び出されます。 ```svelte {#each list as item, index (item)} {item} {/each} ``` カスタムアニメーション関数は `tick` 関数を返すことも可能で、これはアニメーション中に同じ `t` および `u` 引数で呼び出されます。 > [!NOTE] `tick` の代わりに `css` を使用できる場合はそうしてください — web animation はメインスレッド外で実行できるため、遅いデバイスでのカクつきを防ぐことができます。 ```svelte {#each list as item, index (item)} {item} {/each} ``` # style: `style:` ディレクティブは、1つの要素に複数のスタイルを設定するための短縮形の記法を提供します。 ```svelte ... ... ``` 値には任意の式を含めることができます: ```svelte ... ``` 短縮形の形式も使用可能です: ```svelte ... ``` 1つの要素に複数のスタイルを設定することができます: ```svelte ... ``` スタイルを important としてマークするには、`|important` 修飾子を使用します: ```svelte ... ``` `style:` ディレクティブが `style` 属性と組み合わせて使用される場合、ディレクティブが優先されます、 たとえ `!important` プロパティが指定されていてもです: ```svelte This will be red This will still be red ``` # class 要素にクラスを設定する方法は2つあります: `class` 属性と `class:` ディレクティブです。 ## Attributes プリミティブな値は他の属性と同じように扱われます: ```svelte ... ``` > [!NOTE] > 歴史的な理由により、falsy な値 (例えば `false` や `NaN`) は文字列化されます (`class="false"`) が、`class={undefined}` (または `null`) の場合、属性が完全に省略されます。将来の Svelte バージョンでは、すべての falsy の値で `class` が省略されるようになります。 ### Objects and arrays Svelte 5.16以降、`class` はオブジェクトや配列で指定でき、[clsx](https://github.com/lukeed/clsx) で文字列に変換されます。 値がオブジェクトの場合、truthy なキーが追加されます: ```svelte ... ``` 値が配列の場合、truthy な値が結合されます: ```svelte ... ``` 配列形式でもオブジェクト形式でも、1つの条件で複数のクラスを同時に設定できます。これは、Tailwind のようなものを使用している場合に特に便利です。 配列は配列やオブジェクトを含むことができ、clsx がそれらをフラットにします。例えば、ローカルクラスと props を組み合わせる際に便利です: ```svelte {@render props.children?.()} ``` このコンポーネントのユーザーは、オブジェクト、配列、文字列を混在させる柔軟性を得ることができます: ```svelte useTailwind = true} class={{ 'bg-blue-700 sm:w-1/2': useTailwind }} > Accept the inevitability of Tailwind ``` Svelte はまた、要素の `class` 属性が受け入れる値の型である `ClassValue` 型を公開しています。これは、コンポーネントの props に型安全なクラス名を使用したい場合に便利です: ```svelte ... ``` ## The `class:` directive Svelte 5.16以前では、`class:` ディレクティブは条件付きで要素にクラスを設定する最も便利な方法でした。 ```svelte ... ... ``` 他のディレクティブと同様に、クラス名が値と一致する場合は短縮形を使用できます: ```svelte ... ``` > [!NOTE] 古いバージョンの Svelte を使用していない限り、`class:` を避けることを検討してください。属性の方がより強力でコンポーザブル (composable) だからです。 # await As of Svelte 5.36, you can use the `await` keyword inside your components in three places where it was previously unavailable: - at the top level of your component's ` {a} + {b} = {await add(a, b)} ``` ...if you increment `a`, the contents of the `` will _not_ immediately update to read this — ```html 2 + 2 = 3 ``` — instead, the text will update to `2 + 2 = 4` when `add(a, b)` resolves. Updates can overlap — a fast update will be reflected in the UI while an earlier slow update is still ongoing. ## Concurrency Svelte will do as much asynchronous work as it can in parallel. For example if you have two `await` expressions in your markup... ```svelte {await one()} {await two()} ``` ...both functions will run at the same time, as they are independent expressions, even though they are _visually_ sequential. This does not apply to sequential `await` expressions inside your ` {#if error} { error = null; reset(); }}> oops! try again {/if} ``` `onerror` 関数内でエラーが発生した場合 (またはエラーを再スローした場合)、もし親の boundary が存在すればそこで処理されます。 # ```svelte ``` ```svelte ``` `` 要素を使用すると、コンポーネントが破棄される際にイベントリスナーを削除する手間や、サーバーサイドレンダリング時に `window` の存在を確認する必要がなく、`window` オブジェクトにイベントリスナーを追加することができます。 この要素はコンポーネントのトップレベルにのみ配置できます — ブロックや他の要素の中に含めることはできません。 ```svelte ``` 以下のプロパティにもバインドできます: - `innerWidth` - `innerHeight` - `outerWidth` - `outerHeight` - `scrollX` - `scrollY` - `online` — an alias for `window.navigator.onLine` - `devicePixelRatio` `scrollX` と `scrollY` を除くすべてのプロパティは読取専用です。 ```svelte ``` > [!NOTE] アクセシビリティの問題を避けるため、ページは初期値にスクロールされません。`scrollX` や `scrollY` にバインドされた変数の変更があった場合のみスクロールが発生します。コンポーネントがレンダリングされたときにスクロールを発生させる正当な理由がある場合は、`$effect` 内で `scrollTo()` を呼び出してください。 # ```svelte ``` ```svelte ``` `` と似ていますが、この要素を使用すると `window` では発火しない `visibilitychange` などの `document` のイベントにリスナーを追加できます。また、`document` に対して [action](use) を使用することも可能です。 `` と同様に、この要素はコンポーネントのトップレベルにのみ配置でき、ブロックや他の要素の中に含めることはできません。 ```svelte ``` 以下のプロパティにもバインドできます: - `activeElement` - `fullscreenElement` - `pointerLockElement` - `visibilityState` すべて読取専用です。 # ```svelte ``` `` と似ていますが、この要素では、`window` では発火しない `mouseenter` や `mouseleave` などの `document.body` のイベントにリスナーを追加することができます。また、`` 要素で [action](use) を使用することもできます。 `` や `` と同様に、この要素はコンポーネントのトップレベルにのみ配置でき、ブロックや他の要素の中に含めることはできません。 ```svelte ``` # ```svelte ... ``` この要素を使用すると、`document.head` 内に要素を挿入できます。サーバーサイドレンダリング時には、`head` の内容は `body` の主要なコンテンツとは別に出力されます。 ``、``、`` と同様に、この要素はコンポーネントのトップレベルにのみ配置でき、ブロックや他の要素の中に含めることはできません。 ```svelte Hello world! ``` # ```svelte ``` `` 要素を使用すると、開発中には不明な要素 (例えば CMS から提供される要素) をレンダリングできます。プロパティやイベントリスナーを指定した場合は、その要素に適用されます。 Svelte の組み込みバインディングはジェネリックな要素には対応していないため、唯一サポートされているバインディングは `bind:this` です。 `this` に nullish な値が設定されている場合、その要素とその子要素はレンダリングされません。 `this` に [void element(空要素)](https://developer.mozilla.org/ja/docs/Glossary/Void_element) (例えば `br`) のタグ名が指定されており、`` に子要素が含まれている場合、開発モードの場合は実行時エラーが発生します: ```svelte This text cannot appear inside an hr element ``` Svelte は可能な限り要素の周囲の状況から適切な名前空間を推測しようとしますが、常に正しく推測できるとは限りません。そのため、`xmlns` 属性を使用して明示的に指定することができます: ```svelte ``` `this` には有効な DOM 要素のタグを指定する必要があります。例えば `#text` や `svelte:head` などは使用できません。 # ```svelte ``` `` 要素を使用すると、コンポーネントごとのコンパイラオプションを指定できます。詳細は [コンパイラのセクション](svelte-compiler#compile) に記載されています。使用可能なオプションは以下のとおりです: - `runes={true}` — コンポーネントを _runes モード_ に強制します ([Legacy APIs](legacy-overview) セクションを参照) - `runes={false}` — コンポーネントを _レガシーモード_ に強制します - `namespace="..."` — このコンポーネントが使用される名前空間を指定します。デフォルトは "html" で、"svg" や "mathml" も指定可能です。 - `customElement={...}` — このコンポーネントを custom element としてコンパイルする際に使用する [オプション](custom-elements#Component-options) を指定します。文字列を渡すと、それが `tag` オプションとして使用されます。 - `css="injected"` — コンポーネントのスタイルをインラインで挿入します。サーバーサイドレンダリング時には `head` 内に ` ``` ### custom_element_props_identifier ``` Using a rest element or a non-destructured declaration with `$props()` means that Svelte can't infer what properties to expose when creating a custom element. Consider destructuring all the props or explicitly specifying the `customElement.props` option. ``` ### element_implicitly_closed ``` This element is implicitly closed by the following `%tag%`, which can cause an unexpected DOM structure. Add an explicit `%closing%` to avoid surprises. ``` In HTML, some elements are implicitly closed by another element. For example, you cannot nest a `` inside another ``: ```html hello hello ``` Similarly, a parent element's closing tag will implicitly close all child elements, even if the `` was a typo and you meant to create a _new_ element. To avoid ambiguity, it's always a good idea to have an explicit closing tag. ### element_invalid_self_closing_tag ``` Self-closing HTML tags for non-void elements are ambiguous — use `<%name% ...>%name%>` rather than `<%name% ... />` ``` In HTML, there's [no such thing as a self-closing tag](https://jakearchibald.com/2023/against-self-closing-tags-in-html/). While this _looks_ like a self-contained element with some text next to it... ```html some text! ``` ...a spec-compliant HTML parser (such as a browser) will in fact parse it like this, with the text _inside_ the icon: ```html some text! ``` Some templating languages (including Svelte) will 'fix' HTML by turning `` into ``. Others adhere to the spec. Both result in ambiguity and confusion when copy-pasting code between different contexts, and as such Svelte prompts you to resolve the ambiguity directly by having an explicit closing tag. To automate this, run the dedicated migration: ```sh npx sv migrate self-closing-tags ``` In a future version of Svelte, self-closing tags may be upgraded from a warning to an error. ### event_directive_deprecated ``` Using `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead ``` See [the migration guide](v5-migration-guide#Event-changes) for more info. ### export_let_unused ``` Component has unused export property '%name%'. If it is for external reference only, please consider using `export const %name%` ``` ### legacy_code ``` `%code%` is no longer valid — please use `%suggestion%` instead ``` ### legacy_component_creation ``` Svelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead. ``` See the [migration guide](v5-migration-guide#Components-are-no-longer-classes) for more info. ### node_invalid_placement_ssr ``` %message%. When rendering this component on the server, the resulting HTML will be modified by the browser (by moving, removing, or inserting elements), likely resulting in a `hydration_mismatch` warning ``` HTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples: - `hello world` will result in `hello world` (the `` autoclosed the `` because `` cannot contain block-level elements) - `option a` will result in `option a` (the `` is removed) - `cell` will result in `cell` (a `` is auto-inserted) This code will work when the component is rendered on the client (which is why this is a warning rather than an error), but if you use server rendering it will cause hydration to fail. ### non_reactive_update ``` `%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates ``` This warning is thrown when the compiler detects the following: - a variable was declared without `$state` or `$state.raw` - the variable is reassigned - the variable is read in a reactive context In this case, changing the value will not correctly trigger updates. Example: ```svelte This value updates: {reactive} This value does not update: {stale} { stale = 'updated'; reactive = 'updated'; }}>update ``` To fix this, wrap your variable declaration with `$state`. ### options_deprecated_accessors ``` The `accessors` option has been deprecated. It will have no effect in runes mode ``` ### options_deprecated_immutable ``` The `immutable` option has been deprecated. It will have no effect in runes mode ``` ### options_missing_custom_element ``` The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option? ``` ### options_removed_enable_sourcemap ``` The `enableSourcemap` option has been removed. Source maps are always generated now, and tooling can choose to ignore them ``` ### options_removed_hydratable ``` The `hydratable` option has been removed. Svelte components are always hydratable now ``` ### options_removed_loop_guard_timeout ``` The `loopGuardTimeout` option has been removed ``` ### options_renamed_ssr_dom ``` `generate: "dom"` and `generate: "ssr"` options have been renamed to "client" and "server" respectively ``` ### perf_avoid_inline_class ``` Avoid 'new class' — instead, declare the class at the top level scope ``` ### perf_avoid_nested_class ``` Avoid declaring classes below the top level scope ``` ### reactive_declaration_invalid_placement ``` Reactive declarations only exist at the top level of the instance script ``` ### reactive_declaration_module_script_dependency ``` Reassignments of module-level declarations will not cause reactive statements to update ``` ### script_context_deprecated ``` `context="module"` is deprecated, use the `module` attribute instead ``` ```svelte ``` ### script_unknown_attribute ``` Unrecognized attribute — should be one of `generics`, `lang` or `module`. If this exists for a preprocessor, ensure that the preprocessor removes it ``` ### slot_element_deprecated ``` Using `` to render parent content is deprecated. Use `{@render ...}` tags instead ``` See [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info. ### state_referenced_locally ``` This reference only captures the initial value of `%name%`. Did you mean to reference it inside a %type% instead? ``` This warning is thrown when the compiler detects the following: - A reactive variable is declared - ...and later reassigned... - ...and referenced in the same scope This 'breaks the link' to the original state declaration. For example, if you pass the state to a function, the function loses access to the state once it is reassigned: ```svelte count++}> increment ``` ```svelte The count is {count} ``` To fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function: ```svelte count++}> increment ``` ```svelte The count is {+++count()+++} ``` For more info, see [Passing state into functions]($state#Passing-state-into-functions). ### store_rune_conflict ``` It looks like you're using the `$%name%` rune, but there is a local binding called `%name%`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `%name%` to avoid the ambiguity ``` ### svelte_component_deprecated ``` `` is deprecated in runes mode — components are dynamic by default ``` In previous versions of Svelte, the component constructor was fixed when the component was rendered. In other words, if you wanted `` to re-render when `X` changed, you would either have to use `` or put the component inside a `{#key X}...{/key}` block. In Svelte 5 this is no longer true — if `X` changes, `` re-renders. In some cases `` syntax can be used as a replacement; a lowercased variable with property access is recognized as a component in Svelte 5. For complex component resolution logic, an intermediary, capitalized variable may be necessary. E.g. in places where `@const` can be used: ```svelte {#each items as item} ------ +++{@const Component = item.condition ? Y : Z}+++ ++++++ {/each} ``` A derived value may be used in other contexts: ```svelte ------ ++++++ ``` ### svelte_element_invalid_this ``` `this` should be an `{expression}`. Using a string attribute value will cause an error in future versions of Svelte ``` ### svelte_self_deprecated ``` `` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead ``` See [the note in the docs](legacy-svelte-self) for more info. ### unknown_code ``` `%code%` is not a recognised code ``` ``` `%code%` is not a recognised code (did you mean `%suggestion%`?) ``` # Runtime errors ## Client errors ### async_derived_orphan ``` Cannot create a `$derived(...)` with an `await` expression outside of an effect tree ``` In Svelte there are two types of reaction — [`$derived`](/docs/svelte/$derived) and [`$effect`](/docs/svelte/$effect). Deriveds can be created anywhere, because they run _lazily_ and can be [garbage collected](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection) if nothing references them. Effects, by contrast, keep running eagerly whenever their dependencies change, until they are destroyed. Because of this, effects can only be created inside other effects (or [effect roots](/docs/svelte/$effect#$effect.root), such as the one that is created when you first mount a component) so that Svelte knows when to destroy them. Some sleight of hand occurs when a derived contains an `await` expression: Since waiting until we read `{await getPromise()}` to call `getPromise` would be too late, we use an effect to instead call it proactively, notifying Svelte when the value is available. But since we're using an effect, we can only create asynchronous deriveds inside another effect. ### bind_invalid_checkbox_value ``` Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead ``` ### bind_invalid_export ``` Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`) ``` ### bind_not_bindable ``` A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()` ``` ### component_api_changed ``` Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5 ``` See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. ### component_api_invalid_new ``` Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working. ``` See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. ### derived_references_self ``` A derived value cannot reference itself recursively ``` ### each_key_duplicate ``` Keyed each block has duplicate key at indexes %a% and %b% ``` ``` Keyed each block has duplicate key `%value%` at indexes %a% and %b% ``` ### effect_in_teardown ``` `%rune%` cannot be used inside an effect cleanup function ``` ### effect_in_unowned_derived ``` Effect cannot be created inside a `$derived` value that was not itself created inside an effect ``` ### effect_orphan ``` `%rune%` can only be used inside an effect (e.g. during component initialisation) ``` ### effect_pending_outside_reaction ``` `$effect.pending()` can only be called inside an effect or derived ``` ### effect_update_depth_exceeded ``` Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state ``` If an effect updates some state that it also depends on, it will re-run, potentially in a loop: ```js let count = $state(0); $effect(() => { // this both reads and writes `count`, // so will run in an infinite loop count += 1; }); ``` (Svelte intervenes before this can crash your browser tab.) The same applies to array mutations, since these both read and write to the array: ```js let array = $state(['hello']); $effect(() => { array.push('goodbye'); }); ``` Note that it's fine for an effect to re-run itself as long as it 'settles': ```js let array = ['a', 'b', 'c']; // ---cut--- $effect(() => { // this is okay, because sorting an already-sorted array // won't result in a mutation array.sort(); }); ``` Often when encountering this issue, the value in question shouldn't be state (for example, if you are pushing to a `logs` array in an effect, make `logs` a normal array rather than `$state([])`). In the rare cases where you really _do_ need to write to state in an effect — [which you should avoid]($effect#When-not-to-use-$effect) — you can read the state with [untrack](svelte#untrack) to avoid adding it as a dependency. ### flush_sync_in_effect ``` Cannot use `flushSync` inside an effect ``` The `flushSync()` function can be used to flush any pending effects synchronously. It cannot be used if effects are currently being flushed — in other words, you can call it after a state change but _not_ inside an effect. This restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6. ### get_abort_signal_outside_reaction ``` `getAbortSignal()` can only be called inside an effect or derived ``` ### hydration_failed ``` Failed to hydrate the application ``` ### invalid_snippet ``` Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}` ``` ### lifecycle_legacy_only ``` `%name%(...)` cannot be used in runes mode ``` ### props_invalid_value ``` Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value ``` ### props_rest_readonly ``` Rest element properties of `$props()` such as `%property%` are readonly ``` ### rune_outside_svelte ``` The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files ``` ### set_context_after_init ``` `setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression ``` This restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6. ### state_descriptors_fixed ``` Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`. ``` ### state_prototype_fixed ``` Cannot set prototype of `$state` object ``` ### state_unsafe_mutation ``` Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state` ``` This error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go: ```svelte count++}>{count} {count} is even: {even} {count} is odd: {odd} ``` This is forbidden because it introduces instability: if `{count} is even: {even}` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived: ```js let count = 0; // ---cut--- let even = $derived(count % 2 === 0); let odd = $derived(!even); ``` If side-effects are unavoidable, use [`$effect`]($effect) instead. ### svelte_boundary_reset_onerror ``` A `` `reset` function cannot be called while an error is still being handled ``` If a [``](https://svelte.dev/docs/svelte/svelte-boundary) has an `onerror` function, it must not call the provided `reset` function synchronously since the boundary is still in a broken state. Typically, `reset()` is called later, once the error has been resolved. If it's possible to resolve the error inside the `onerror` callback, you must at least wait for the boundary to settle before calling `reset()`, for example using [`tick`](https://svelte.dev/docs/svelte/lifecycle-hooks#tick): ```svelte { fixTheError(); +++await tick();+++ reset(); }}> ``` ## Server errors ### lifecycle_function_unavailable ``` `%name%(...)` is not available on the server ``` Certain methods such as `mount` cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render. ## Shared errors ### await_outside_boundary ``` Cannot await outside a `` with a `pending` snippet ``` The `await` keyword can only appear in a `$derived(...)` or template expression, or at the top level of a component's ` {#each items as item} {@render children(item)} {/each} ``` Here, `List.svelte` is using `{@render children(item)` which means it expects `Parent.svelte` to use snippets. Instead, `Parent.svelte` uses the deprecated `let:` directive. This combination of APIs is incompatible, hence the error. ### invalid_snippet_arguments ``` A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}` ``` ### lifecycle_outside_component ``` `%name%(...)` can only be used during component initialisation ``` Certain lifecycle methods can only be used during component initialisation. To fix this, make sure you're invoking the method inside the _top level of the instance script_ of your component. ```svelte click me ``` ### snippet_without_render_tag ``` Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`. ``` A component throwing this error will look something like this (`children` is not being rendered): ```svelte {children} ``` ...or like this (a parent component is passing a snippet where a non-snippet value is expected): ```svelte {#snippet label()} Hi! {/snippet} ``` ```svelte {label} ``` ### store_invalid_shape ``` `%name%` is not a store with a `subscribe` method ``` ### svelte_element_invalid_this_value ``` The `this` prop on `` must be a string, if defined ``` # Runtime warnings ## Client warnings ### assignment_value_stale ``` Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour. ``` Given a case like this... ```svelte add items: {JSON.stringify(object.items)} ``` ...the array being pushed to when the button is first clicked is the `[]` on the right-hand side of the assignment, but the resulting value of `object.array` is an empty state proxy. As a result, the pushed value will be discarded. You can fix this by separating it into two statements: ```js let object = { array: [0] }; // ---cut--- function add() { object.array ??= []; object.array.push(object.array.length); } ``` ### await_reactivity_loss ``` Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await` ``` Svelte's signal-based reactivity works by tracking which bits of state are read when a template or `$derived(...)` expression executes. If an expression contains an `await`, Svelte transforms it such that any state _after_ the `await` is also tracked — in other words, in a case like this... ```js let a = Promise.resolve(1); let b = 2; // ---cut--- let total = $derived(await a + b); ``` ...both `a` and `b` are tracked, even though `b` is only read once `a` has resolved, after the initial execution. This does _not_ apply to an `await` that is not 'visible' inside the expression. In a case like this... ```js let a = Promise.resolve(1); let b = 2; // ---cut--- async function sum() { return await a + b; } let total = $derived(await sum()); ``` ...`total` will depend on `a` (which is read immediately) but not `b` (which is not). The solution is to pass the values into the function: ```js let a = Promise.resolve(1); let b = 2; // ---cut--- /** * @param {Promise} a * @param {number} b */ async function sum(a, b) { return await a + b; } let total = $derived(await sum(a, b)); ``` ### await_waterfall ``` An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app ``` In a case like this... ```js async function one() { return 1 } async function two() { return 2 } // ---cut--- let a = $derived(await one()); let b = $derived(await two()); ``` ...the second `$derived` will not be created until the first one has resolved. Since `await two()` does not depend on the value of `a`, this delay, often described as a 'waterfall', is unnecessary. (Note that if the values of `await one()` and `await two()` subsequently change, they can do so concurrently — the waterfall only occurs when the deriveds are first created.) You can solve this by creating the promises first and _then_ awaiting them: ```js async function one() { return 1 } async function two() { return 2 } // ---cut--- let aPromise = $derived(one()); let bPromise = $derived(two()); let a = $derived(await aPromise); let b = $derived(await bPromise); ``` ### binding_property_non_reactive ``` `%binding%` is binding to a non-reactive property ``` ``` `%binding%` (%location%) is binding to a non-reactive property ``` ### console_log_state ``` Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead ``` When logging a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), browser devtools will log the proxy itself rather than the value it represents. In the case of Svelte, the 'target' of a `$state` proxy might not resemble its current value, which can be confusing. The easiest way to log a value as it changes over time is to use the [`$inspect`](/docs/svelte/$inspect) rune. Alternatively, to log things on a one-off basis (for example, inside an event handler) you can use [`$state.snapshot`](/docs/svelte/$state#$state.snapshot) to take a snapshot of the current value. ### event_handler_invalid ``` %handler% should be a function. Did you mean to %suggestion%? ``` ### hydration_attribute_changed ``` The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value ``` Certain attributes like `src` on an `` element will not be repaired during hydration, i.e. the server value will be kept. That's because updating these attributes can cause the image to be refetched (or in the case of an ``, for the frame to be reloaded), even if they resolve to the same resource. To fix this, either silence the warning with a [`svelte-ignore`](basic-markup#Comments) comment, or ensure that the value stays the same between server and client. If you really need the value to change on hydration, you can force an update like this: ```svelte ``` ### hydration_html_changed ``` The value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value ``` ``` The value of an `{@html ...}` block %location% changed between server and client renders. The client value will be ignored in favour of the server value ``` If the `{@html ...}` value changes between the server and the client, it will not be repaired during hydration, i.e. the server value will be kept. That's because change detection during hydration is expensive and usually unnecessary. To fix this, either silence the warning with a [`svelte-ignore`](basic-markup#Comments) comment, or ensure that the value stays the same between server and client. If you really need the value to change on hydration, you can force an update like this: ```svelte {@html markup} ``` ### hydration_mismatch ``` Hydration failed because the initial UI does not match what was rendered on the server ``` ``` Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near %location% ``` This warning is thrown when Svelte encounters an error while hydrating the HTML from the server. During hydration, Svelte walks the DOM, expecting a certain structure. If that structure is different (for example because the HTML was repaired by the DOM because of invalid HTML), then Svelte will run into issues, resulting in this warning. During development, this error is often preceeded by a `console.error` detailing the offending HTML, which needs fixing. ### invalid_raw_snippet_render ``` The `render` function passed to `createRawSnippet` should return HTML for a single element ``` ### legacy_recursive_reactive_block ``` Detected a migrated `$:` reactive block in `%filename%` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an `$effect`. ``` ### lifecycle_double_unmount ``` Tried to unmount a component that was not mounted ``` ### ownership_invalid_binding ``` %parent% passed property `%prop%` to %child% with `bind:`, but its parent component %owner% did not declare `%prop%` as a binding. Consider creating a binding between %owner% and %parent% (e.g. `bind:%prop%={...}` instead of `%prop%={...}`) ``` Consider three components `GrandParent`, `Parent` and `Child`. If you do ``, inside `GrandParent` pass on the variable via `` (note the missing `bind:`) and then do `` inside `Parent`, this warning is thrown. To fix it, `bind:` to the value instead of just passing a property (i.e. in this example do ``). ### ownership_invalid_mutation ``` Mutating unbound props (`%name%`, at %location%) is strongly discouraged. Consider using `bind:%prop%={...}` in %parent% (or using a callback) instead ``` Consider the following code: ```svelte ``` ```svelte ``` `Child` is mutating `person` which is owned by `App` without being explicitly "allowed" to do so. This is strongly discouraged since it can create code that is hard to reason about at scale ("who mutated this value?"), hence the warning. To fix it, either create callback props to communicate changes, or mark `person` as [`$bindable`]($bindable). ### select_multiple_invalid_value ``` The `value` property of a `` element should be an array, but it received a non-array value. The selection will be kept as is. ``` When using ``, Svelte will mark all selected `` elements as selected by iterating over the array passed to `value`. If `value` is not an array, Svelte will emit this warning and keep the selected options as they are. To silence the warning, ensure that `value`: - is an array for an explicit selection - is `null` or `undefined` to keep the selection as is ### state_proxy_equality_mismatch ``` Reactive `$state(...)` proxies and the values they proxy have different identities. Because of this, comparisons with `%operator%` will produce unexpected results ``` `$state(...)` creates a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) of the value it is passed. The proxy and the value have different identities, meaning equality checks will always return `false`: ```svelte ``` To resolve this, ensure you're comparing values where both values were created with `$state(...)`, or neither were. Note that `$state.raw(...)` will _not_ create a state proxy. ### svelte_boundary_reset_noop ``` A `` `reset` function only resets the boundary the first time it is called ``` When an error occurs while rendering the contents of a [``](https://svelte.dev/docs/svelte/svelte-boundary), the `onerror` handler is called with the error plus a `reset` function that attempts to re-render the contents. This `reset` function should only be called once. After that, it has no effect — in a case like this, where a reference to `reset` is stored outside the boundary, clicking the button while `` is rendered will _not_ cause the contents to be rendered again. ```svelte reset (reset = r)}> {#snippet failed(e)} oops! {e.message} {/snippet} ``` ### transition_slide_display ``` The `slide` transition does not work correctly for elements with `display: %value%` ``` The [slide](/docs/svelte/svelte-transition#slide) transition works by animating the `height` of the element, which requires a `display` style like `block`, `flex` or `grid`. It does not work for: - `display: inline` (which is the default for elements like ``), and its variants like `inline-block`, `inline-flex` and `inline-grid` - `display: table` and `table-[name]`, which are the defaults for elements like `` and `` - `display: contents` ## Shared warnings ### dynamic_void_element_content ``` `` is a void element — it cannot have content ``` Elements such as `` cannot have content, any children passed to these elements will be ignored. ### state_snapshot_uncloneable ``` Value cannot be cloned with `$state.snapshot` — the original value was returned ``` ``` The following properties cannot be cloned with `$state.snapshot` — the return value contains the originals: %properties% ``` `$state.snapshot` tries to clone the given value in order to return a reference that no longer changes. Certain objects may not be cloneable, in which case the original value is returned. In the following example, `property` is cloned, but `window` is not, because DOM elements are uncloneable: ```js const object = $state({ property: 'this is cloneable', window }) const snapshot = $state.snapshot(object); ``` # Overview Svelte 5 introduced some significant changes to Svelte's API, including [runes](what-are-runes), [snippets](snippet) and event attributes. As a result, some Svelte 3/4 features are deprecated (though supported for now, unless otherwise specified) and will eventually be removed. We recommend that you incrementally [migrate your existing code](v5-migration-guide). The following pages document these features for - people still using Svelte 3/4 - people using Svelte 5, but with components that haven't yet been migrated Since Svelte 3/4 syntax still works in Svelte 5, we will distinguish between _legacy mode_ and _runes mode_. Once a component is in runes mode (which you can opt into by using runes, or by explicitly setting the `runes: true` compiler option), legacy mode features are no longer available. If you're exclusively interested in the Svelte 3/4 syntax, you can browse its documentation at [v4.svelte.dev](https://v4.svelte.dev). # Reactive let/var declarations In runes mode, reactive state is explicitly declared with the [`$state` rune]($state). In legacy mode, variables declared at the top level of a component are automatically considered _reactive_. Reassigning or mutating these variables (`count += 1` or `object.x = y`) will cause the UI to update. ```svelte count += 1}> clicks: {count} ``` Because Svelte's legacy mode reactivity is based on _assignments_, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to 'tell' the compiler to update the UI: ```svelte ``` # Reactive $: statements In runes mode, reactions to state updates are handled with the [`$derived`]($derived) and [`$effect`]($effect) runes. In legacy mode, any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with a `$:` [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). These statements run after other code in the ` ``` Statements are ordered _topologically_ by their dependencies and their assignments: since the `console.log` statement depends on `sum`, `sum` is calculated first even though it appears later in the source. Multiple statements can be combined by putting them in a block: ```js // @noErrors $: { // recalculate `total` when `items` changes total = 0; for (const item of items) { total += item.value; } } ``` The left-hand side of a reactive assignments can be an identifier, or it can be a destructuring assignment: ```js // @noErrors $: ({ larry, moe, curly } = stooges); ``` ## Understanding dependencies The dependencies of a `$:` statement are determined at compile time — they are whichever variables are referenced (but not assigned to) inside the statement. In other words, a statement like this will _not_ re-run when `count` changes, because the compiler cannot 'see' the dependency: ```js // @noErrors let count = 0; let double = () => count * 2; $: doubled = double(); ``` Similarly, topological ordering will fail if dependencies are referenced indirectly: `z` will never update, because `y` is not considered 'dirty' when the update occurs. Moving `$: z = y` below `$: setY(x)` will fix it: ```svelte ``` ## Browser-only code Reactive statements run during server-side rendering as well as in the browser. This means that any code that should only run in the browser must be wrapped in an `if` block: ```js // @noErrors $: if (browser) { document.title = title; } ``` # export let In runes mode, [component props](basic-markup#Component-props) are declared with the [`$props`]($props) rune, allowing parent components to pass in data. In legacy mode, props are marked with the `export` keyword, and can have a default value: ```svelte ``` The default value is used if it would otherwise be `undefined` when the component is created. > [!NOTE] Unlike in runes mode, if the parent component changes a prop from a defined value to `undefined`, it does not revert to the initial value. Props without default values are considered _required_, and Svelte will print a warning during development if no value is provided, which you can squelch by specifying `undefined` as the default value: ```js export let foo +++= undefined;+++ ``` ## Component exports An exported `const`, `class` or `function` declaration is _not_ considered a prop — instead, it becomes part of the component's API: ```svelte ``` ```svelte greeter.greet('world')}> greet ``` ## Renaming props The `export` keyword can appear separately from the declaration. This is useful for renaming props, for example in the case of a reserved word: ```svelte ``` # $$props and $$restProps In runes mode, getting an object containing all the props that were passed in is easy, using the [`$props`]($props) rune. In legacy mode, we use `$$props` and `$$restProps`: - `$$props` contains all the props that were passed in, including ones that are not individually declared with the `export` keyword - `$$restProps` contains all the props that were passed in _except_ the ones that were individually declared For example, a `` component might need to pass along all its props to its own `` element, except the `variant` prop: ```svelte click me ``` In Svelte 3/4 using `$$props` and `$$restProps` creates a modest performance penalty, so they should only be used when needed. # on: In runes mode, event handlers are just like any other attribute or prop. In legacy mode, we use the `on:` directive: ```svelte count: {count} ``` Handlers can be declared inline with no performance penalty: ```svelte (count += 1)}> count: {count} ``` Add _modifiers_ to element event handlers with the `|` character. ```svelte ``` The following modifiers are available: - `preventDefault` — calls `event.preventDefault()` before running the handler - `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element - `stopImmediatePropagation` - calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired. - `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) - `nonpassive` — explicitly set `passive: false` - `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase - `once` — remove the handler after the first time it runs - `self` — only trigger handler if `event.target` is the element itself - `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action. Modifiers can be chained together, e.g. `on:click|once|capture={...}`. If the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it. ```svelte The component itself will emit the click event ``` It's possible to have multiple event listeners for the same event: ```svelte clicks: {count} ``` ## Component events Components can dispatch events by creating a _dispatcher_ when they are initialised: ```svelte dispatch('decrement')}>decrement dispatch('increment')}>increment ``` `dispatch` creates a [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). If a second argument is provided, it becomes the `detail` property of the event object. A consumer of this component can listen for the dispatched events: ```svelte n -= 1} on:increment={() => n += 1} /> n: {n} ``` Component events do not bubble — a parent component can only listen for events on its immediate children. Other than `once`, modifiers are not valid on component event handlers. > [!NOTE] > If you're planning an eventual migration to Svelte 5, use callback props instead. This will make upgrading easier as `createEventDispatcher` is deprecated: > > ```svelte > > > > decrement > increment > ``` # In Svelte 5, content can be passed to components in the form of [snippets](snippet) and rendered using [render tags](@render). In legacy mode, content inside component tags is considered _slotted content_, which can be rendered by the component using a `` element: ```svelte This is some slotted content ``` ```svelte ``` > [!NOTE] If you want to render a regular `` element, you can use ``. ## Named slots A component can have _named_ slots in addition to the default slot. On the parent side, add a `slot="..."` attribute to an element, component or [``](legacy-svelte-fragment) directly inside the component tags. ```svelte {#if open} This is some slotted content ++++++ open = false}> close ++++++ {/if} ``` On the child side, add a corresponding `` element: ```svelte ++++++ ``` ## Fallback content If no slotted content is provided, a component can define fallback content by putting it inside the `` element: ```svelte This will be rendered if no slotted content is provided ``` ## Passing data to slotted content Slots can be rendered zero or more times and can pass values _back_ to the parent using props. The parent exposes the values to the slot template using the `let:` directive. ```svelte {#each items as data} {/each} ``` ```svelte {processed.text} ``` The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `` is equivalent to ``. Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute. ```svelte {#each items as item} {/each} ``` ```svelte {item.text} Copyright (c) 2019 Svelte Industries ``` # $$slots In runes mode, we know which [snippets](snippet) were provided to a component, as they're just normal props. In legacy mode, the way to know if content was provided for a given slot is with the `$$slots` object, whose keys are the names of the slots passed into the component by the parent. ```svelte {#if $$slots.description} {/if} ``` ```svelte Blog Post Title ``` # The `` element allows you to place content in a [named slot](legacy-slots) without wrapping it in a container DOM element. This keeps the flow layout of your document intact. ```svelte No header was provided Some content between header and footer ``` ```svelte Hello All rights reserved. Copyright (c) 2019 Svelte Industries ``` > [!NOTE] > In Svelte 5+, this concept is obsolete, as snippets don't create a wrapping element # In runes mode, `` will re-render if the value of `MyComponent` changes. See the [Svelte 5 migration guide](/docs/svelte/v5-migration-guide#svelte:component-is-no-longer-necessary) for an example. In legacy mode, it won't — we must use ``, which destroys and recreates the component instance when the value of its `this` expression changes: ```svelte ``` If `this` is falsy, no component is rendered. # The `` element allows a component to include itself, recursively. It cannot appear at the top level of your markup; it must be inside an if or each block or passed to a component's slot to prevent an infinite loop. ```svelte {#if count > 0} counting down... {count} {:else} lift-off! {/if} ``` > [!NOTE] > This concept is obsolete, as components can import themselves: > ```svelte > > > > {#if count > 0} > counting down... {count} > > {:else} > lift-off! > {/if} > ``` # Imperative component API In Svelte 3 and 4, the API for interacting with a component is different than in Svelte 5. Note that this page does _not_ apply to legacy mode components in a Svelte 5 application. ## Creating a component ```ts // @noErrors const component = new Component(options); ``` A client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class. ```ts // @noErrors import App from './App.svelte'; const app = new App({ target: document.body, props: { // assuming App.svelte contains something like // `export let answer`: answer: 42 } }); ``` The following initialisation options can be provided: | option | default | description | | --------- | ----------- | ---------------------------------------------------------------------------------------------------- | | `target` | **none** | An `HTMLElement` or `ShadowRoot` to render to. This option is required | | `anchor` | `null` | A child of `target` to render the component immediately before | | `props` | `{}` | An object of properties to supply to the component | | `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component | | `hydrate` | `false` | See below | | `intro` | `false` | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes | Existing children of `target` are left where they are. The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](/docs/svelte-compiler#compile). Hydration of `` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `` so that the component knows which elements it's responsible for removing during hydration. Whereas children of `target` are normally left alone, `hydrate: true` will cause any children to be removed. For that reason, the `anchor` option cannot be used alongside `hydrate: true`. The existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes. ```ts /// file: index.js // @noErrors import App from './App.svelte'; const app = new App({ target: document.querySelector('#server-rendered-html'), hydrate: true }); ``` > [!NOTE] > In Svelte 5+, use [`mount`](svelte#mount) instead ## `$set` ```ts // @noErrors component.$set(props); ``` Programmatically sets props on an instance. `component.$set({ x: 1 })` is equivalent to `x = 1` inside the component's `