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コンポーネントの非同期読み込み方法でした。