KINTO Tech Blog
Development

SvelteTips - Irregular Svelte series 05

Cover Image for SvelteTips - Irregular Svelte series 05

Svelte Tips

Hello (or good evening), this is part 5 of our irregular Svelte series. Click here to see the other articles:

  1. Insights from using SvelteKit + Svelte for a year
  2. Comparison of Svelte and other JS frameworks - Irregular Svelte series-01
  3. Svelte unit test - Irregular Svelte series 02
  4. Using Storybook with Svelte - Irregular Svelte Series 03
  5. Exploring Svelte in Astro - Irregular Svelte series 04
  6. SvelteTips - Irregular Svelte series 05

That's a lot of articles so far!

This time, I will use the project we have in the previous articles and explain parts where you may go be like, "I'm stuck!" "what to do?" in a way that is easy to understand. The table of contents looks as follows:

  • SSG Settings
  • Differences Between .page.ts and .server.ts
  • meta and How to Use It (About the Plugin)
  • What is Used in Each Life Cycle

SSG Settings

With SvelteKit, you can easily configure deployment destinations by using a module called Adapter. The default is an SSR adapter called adapter-auto, so you need to install a module called adapter-static.

I remember being stuck at first and wracking my brain. It was named "auto," so it must do something.

But that was not the case.

By just implementing adapter-static and writing the code in the documentation, I quickly created a build file optimized for static hosting (note to self to read documentations properly...)

The official site of Svelte has a Japanese translation of PJ, so having translated documentation available was very helpful :)

svelte.config.js
// without this, you can't build as an SSG
import adapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  // omitted
	kit: {
		adapter: adapter({
			pages: 'build',
			assets: 'build',
			fallback: null,
			precompress: false,
			strict: true
		})
	}
};

export default config;

Details: https://kit.svelte.jp/docs/adapter-static

Differences Between .page.ts and .server.ts

This was a setback when SvelteKit v1 was released and it changed significantly. It was a radical change, so you might remember it.

Since the release of v1, SvelteKit inserts the following two files by default when fetching data in a page.

  • *.svelte => Files such as UI
  • *.page.server.ts || *.page.ts => a file that defines data such as fetch

The files that define data are divided into page.ts and page.server.ts.

I didn't understand the difference between *.page.ts and *.page.server.ts at first, so I opted for SSG. However, during transitions, it began fetching data from the API .... Like whaat?!

For *.page.ts, it runs on both client-side and server-side

For *.page.server.ts, it runs only on the server-side

So, if you want to JAMSTACK with SSG, *page.server.ts is the right way to go.

https://kit.svelte.jp/docs/load#universal-vs-server

So again, please read the documentation! The documentation is great.

Correct example of running only on the server side

src/routes/+page.server.ts
export async function load({ params, fetch }) {
	const pagesReq = await fetch(`APIURL`);
	let data = await pagesReq.json();
	return {
		data
	};
}

How to Manage meta

Managing meta information poses a common challenge for all frameworks and websites.

Before discovering the framework, I used to laboriously work with the trifecta Pug, JSON, and Gulp or Webpack, but with Svelte it became easier to deal with them.

src/components/Meta.Svelte
<script lang="ts">
  import { siteTitle, siteDescription } from '$lib/config';
  interface META {
    title: string;
    description?: string;
  }

  export let metadata: META;
</script>

<title>{`${metadata.title}${siteTitle}`}</title>

{#if metadata.description}
  <meta name="description" content={metadata.description} />
{:else}
  <meta name="description" content={siteDescription} />
{/if}
src/routes/+page.svelte
<script lang="ts">
  import Meta from '$lib/components/Meta.svelte';

  let metadata = {
    title: 'title, title, title',
    description: 'description, description, description, description'
  };
</script>

<Meta {metadata} />

You can create and load a meta component like this.

You don't have to make it yourself as there are wonderful plugins such as this one out there.
https://github.com/oekazuma/svelte-meta-tags

Thank you kind stranger!!!!

On the Usefulness at Each Life Cycle

Finally, the unavoidable life cycle functions

Svelte has five life cycle functions: onMount, onDestroy, beforeUpdate, afterUpdate, and tick.

onMount

As the name implies, this is executed after the component is initially rendered to the DOM. Timing is almost the same as mounted hook in Vue.

onDestroy

As the name implies, this is also executed when the component is destroyed. You can prevent memory leaks by discarding components when processing is no longer necessary.

Also, for server-side components, only this lifecycle function is available.

beforeUpdate

This component is a lifecycle function used before the DOM is rendered. Also, beforeUpdate is used often when you want to reflect state changes first.

Since this life cycle function is used before the DOM is rendered, you need to be careful when writing processing related to the DOM.

afterUpdate

This function is executed after the component is rendered by the DOM and the data is reflected.
It's the last life cycle function to be found on Svelte.

tick

You can handle the timing after a state is updated and before the state is rendered into the DOM. It is possible to wait for the DOM to be updated before processing anything.

It is relatively easy to understand because it has fewer life cycle functions than other frameworks.

This would be all for now on my Svelte Tips article today.

Conclusion

I wrote a special article about Svelte titled "Getting Started with Svelte" in the July 2023 issue of Software Design, a Japanese Magazine. Please feel free to give it a read if you're interested :)
(It also includes a tutorial to JAMSTACK in SSG, so give it a try!)

https://twitter.com/gihyosd/status/1669533941483864072?s=20

Facebook

関連記事 | Related Posts

We are hiring!

【フロントエンドエンジニア(コンテンツ開発)】新車サブスク開発G/東京

新車サブスク開発グループについてTOYOTAのクルマのサブスクリプションサービスである『 KINTO ONE 』のWebサイトの開発、運用をしています。​業務内容トヨタグループの金融、モビリティサービスの内製開発組織である同社にて、自社サービスである、クルマのサブスクリプションサービス『KINTO ONE』のWebサイトコンテンツの開発・運用業務を担っていただきます。

【フロントエンドエンジニア】新車サブスク開発G/東京

新車サブスク開発グループについてTOYOTAのクルマのサブスクリプションサービスである『 KINTO ONE 』のWebサイトの開発、運用をしています。​業務内容トヨタグループの金融、モビリティサービスの内製開発組織である同社にて、自社サービスである、TOYOTAのクルマのサブスクリプションサービス『KINTO ONE』のWebサイトの開発、運用を行っていただきます。