명령형 컴포넌트 API(Imperative Component API)
명령형 컴포넌트 API(Imperative Component API)
모든 Svelte 애플리케이션은 명령형(imperative)으로 루트 컴포넌트를 생성하는 것으로 시작해요. 클라이언트에서는 컴포넌트를 특정 요소에 마운트하고, 서버에서는 대신 렌더링할 HTML 문자열을 얻고 싶을 거예요. 이를 돕는 함수들을 정리할게요.
mount
컴포넌트를 인스턴스화하고 주어진 target에 마운트해요.
import { mount } from 'svelte';
import App from './App.svelte';
const app = mount(App, {
target: document.querySelector('#app'),
props: { some: 'property' },
});
Svelte 4에서 new App(...)을 호출할 때와 달리, mount 중에는 이펙트(onMount 콜백, action 함수 포함)가 실행되지 않아요. 테스트 맥락에서 보류 중인 이펙트를 강제로 실행하려면 flushSync()를 쓰면 돼요.
unmount
마운트된 컴포넌트를 언마운트해서 정리하고 자원을 해제해요.
render
서버에서만, 그리고 server 옵션으로 컴파일했을 때만 사용할 수 있어요. 컴포넌트를 받아 body와 head 속성을 가진 객체를 반환해서, 서버 렌더링 시 HTML을 채우는 데 쓸 수 있어요.
import { render } from 'svelte/server';
import App from './App.svelte';
const result = render(App, { props: { some: 'property' } });
hydrate
mount와 같지만, Svelte의 SSR 출력(render 함수 출력)으로 렌더링된 target 안의 HTML을 재사용해서 상호작용하게 만들어요.
import { hydrate } from 'svelte';
import App from './App.svelte';
const app = hydrate(App, {
target: document.querySelector('#app'),
props: { some: 'property' },
});
mount와 마찬가지로 hydrate 중에도 이펙트는 실행되지 않으니, 필요하면 직후에 flushSync()를 사용하세요.
더 알아보기
- 라이프사이클 훅: https://svelte.dev/docs/svelte/lifecycle-hooks
- What are runes?: https://svelte.dev/docs/svelte/what-are-runes
- Getting started: https://svelte.dev/docs/svelte/getting-started