Skip to main content

Svelte를 통한 프론트엔드 개선 검토

reference: https://svelte.dev/tutorial/basics

who: Alex

Untitled

Sevelte는 대부분의 작업을 브라우저에서만 수행하던 react, vue와 달리 컴파일 단계로 작업을 전환하고 virtual dom 을 업데이트 하는 것이 아닌 dom 을 업데이트하는 방식으로 동작합니다.

특징

  1. code 를 적게 쓸 수 있도록 설계된 프레임워크
  2. compile 을 프레임워크가 없는 가벼운 vanilla JS 로 수행해 빠르게 시작하고 빠른 성능을 유지
  3. 복잡한 상태 관리가 필요 업고 javascript 자체에 반응하도록 설계

사용법

<script>
import Nested from "./Nested.svelte";
let test = 'this is string!';
function changeString() {
test = 'change string';
}
</script>

<Nested />
<p>This is a paragraph {test}.</p>
<button on:click={changeString}>change</button>

<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>
  • svelte는 기본적으로 html, css, javascript 동작과 거의 같다. script 태그 안에 javascript 동작을 정의하고 중간에 특정 태그 없이 작성하고 style 태그 안에 css 를 작성
  • on: 을 이용해 DOM 이벤트를 관리
<ul>
{#each cats as cat}
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
{cat.name}
</a></li>
{/each}
</ul>
  • for each 를 간단하게 구현하도록 하는 #each statement 가 존재해 간단한 코드로 구현 가능함.
{#if x > 10}
<p>{x} is greater than 10</p>
{:else if 5 > x}
<p>{x} is less than 5</p>
{:else}
<p>{x} is between 5 and 10</p>
{/if}
  • if, else도 #if statement 를 활용해 간단히 구현
{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
  • await도 #await statement 를 활용해 간단히 구현
import { writable } from 'svelte/store';

export const count = writable(0);
export const increment = () => {
count.update(n => n + 1);
}
export const reset() {
const cnt = count.get()
if(cnt) {
count.set(0)
}
}
  • svelte/store 에서 제공 기능들을 이용해 간단하게 global state 관리를 구현
<script>
import { fly } from 'svelte/transition';
let visible = true;
</script>

<label>
<input type="checkbox" bind:checked={visible}>
visible
</label>

{#if visible}
<p transition:fly="{{ y: 200, duration: 2000 }}">
Flies in and out
</p>
{/if}
  • svelte/transition 에서 제공 기능들을 통해 간단한 애니메이션 구현

이 외에도 수 많은 기능들이 있지만 위의 기능만으로도 웬만한 웹싸이트 구현에 문제가 없고 개발 속도 뿐만 아니라 페이지 속도 또한 빠르고 가볍게 잘 동작