3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Svelteコンポーネントの非同期読み込み

特に説明することがないので答えを書きます!

{#await import('$lib/Counter.svelte') then { default: Counter }}
  <Counter initialCount={1} />
{/await}

コンポーネントは特に何も考えずいつも通り作ってしまって問題ありません。
propsも もちろん渡せます。

ちょっと説明

SvelteコンポーネントはこちらのJS outputを見て分かる通り、export defaultされた関数です。

awaitブロックでimportし、Promiseが解決したらdefaultという名前で受け取ることができます。
<default />だとちょっとコンポーネントっぽくないので、{ default: Counter }の部分でCounterという名前をつけました。
コンポーネントっぽいですね〜

今回はコンポーネントを非同期読み込みしましたが、
例えば

export function hoge(){ return 'hoge' }

こういう関数をimportする場合は

{#await import('$lib/hoge.ts') then { hoge }}
  {hoge()}
{/await}

のように書くことができます。

今回紹介したコードはSvelteLabにあります。
以上、Svelteコンポーネントの非同期読み込み方法でした。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?