JavaScriptプログラムに関する各種メモ書き

svelte + TypeScript のはじめ方

● svelte のインストール

npx degit sveltejs/template my-svelte-app
cd my-svelte-app
node scripts/setupTypeScript.js
npm install

● ポートを5001に変更する(macの場合)

package.json

    "start": "sirv public --no-clear",

  ↓

    "start": "sirv public --no-clear --port 5001",

● 起動する

npm run dev

● Svelteコンポーネントを作成する

src/components/Header.svelte を以下の内容で作成する

変数を export することによってプロップスとして受け取ることができます

<script lang="ts">
  export let headerTitle: string;
</script>

<div>
    <h1>app header ({headerTitle})</h1>
</div>

App.Svelte から呼び出す

<Header headerTitle="タイトルのテスト"/>

● ビルドする

npm run build

index.html のパス表記を相対パスにするとサーバーなしで起動することができます。

● アプリの適用htmlタグを指定する

デフォルトではbodyタグにアプリが展開されますがタグを指定することができます.

main.ts

const app = new App({
  target: document.body,
});

  ↓

main.ts
id="svelteapp" のタグに展開する

const app = new App({
  target: document.querySelector('#svelteapp'),
});

● htmlからpropsを渡す

const app = new App({
  target: document.querySelector('#svelteapp'),
  props: {
    titleFromHtml: document
      .getElementById('svelteapp')
      .getAttribute('data-title'),
  },
});

とすると

	<div id="svelteapp" data-title="タイトル流し込み"></div>

の値を渡すことができます。

● Storeを使用する

Storeの定義 stores.ts

import { writable } from 'svelte/store';

export interface UserStore {
  code: string
  name: string
}

export const userStore = writable<UserStore>({
  code: "user0001",
  name: "hogefuga"
});

Storeのsubscribe(ストアのオブジェクトに変更がある度に指定したコールバックが呼ばれます) App.svelte

	import {UserStore, userStore} from './stores.ts';
  
	// userStore
	let user:UserStore;
	userStore.subscribe(u => {
                // コールバック
		user = {
			code: u.code,
			name: u.name,
		};
	});

Storeから取得した値の参照 App.svelte

	<div style="font-weight: bold;"> code: {user.code} </div>
	<div style="font-weight: bold;"> name: {user.name} </div>

Storeの更新 App.svelte

  userStore.update((s) => {
    return {
			code: ’code999’,
			name: 'テスト太郎',
		};
  });

● スコープされていないグローバルなcssを適用する

<style>
    :global(div.content) {
        height: 690px;
    }
</style>

参考 : https://zenn.dev/miruoon_892/articles/2c9efd2c302c56bd41a6
引用 : https://zenn.dev/dictav/articles/sapper-web-app#store
参考 : https://qiita.com/tonio0720/items/88e62e6beffa9adc1a7f
参考: https://qiita.com/tonio0720/items/34ecaae10a67fab3ab16

No.2193
08/24 10:09

edit