3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今流行りのSvelteKitを使ってみたい、そしてContentfulも活かしたい、でもContentful公式のスターターはなんか古い!
ので、下記はSvelteKitでContentfulのデータを取得して表示するためせっせと調べながらやったメモです。

SvelteKitを入れる

SvelteKitのドキュメントを頼りにnpm create svelte@latestなどしてSvelteKitを入れる。

package.json
{
	"name": "svelte",
	"version": "0.0.1",
	"private": true,
	"scripts": {
		"dev": "vite dev",
		"build": "vite build",
		"preview": "vite preview",
		"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
		"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
		"lint": "prettier --check . && eslint .",
		"format": "prettier --write ."
	},
	"devDependencies": {
		"@sveltejs/adapter-auto": "^3.0.0",
		"@sveltejs/kit": "^2.0.0",
		"@sveltejs/vite-plugin-svelte": "^3.0.0",
		"@types/eslint": "^8.56.7",
		"eslint": "^9.0.0",
		"eslint-config-prettier": "^9.1.0",
		"eslint-plugin-svelte": "^2.36.0",
		"globals": "^15.0.0",
		"prettier": "^3.1.1",
		"prettier-plugin-svelte": "^3.1.2",
		"svelte": "^4.2.7",
		"svelte-check": "^3.6.0",
		"tslib": "^2.4.1",
		"typescript": "^5.0.0",
		"typescript-eslint": "^8.0.0-alpha.20",
		"vite": "^5.0.3"
	},
	"type": "module",
}

Contentfulのトークンまわりを準備する

Space settingsで確認できるSpace IDContent Delivery APIを準備し、.envに転記する。

.env
CONTENTFUL_SPACE_ID = 
CONTENTFUL_ACCESS_TOKEN = 

ContentfulのSDKを入れてデータを取得する

$ npm install contentful
src/lib/contentful.ts
import contentful from 'contentful';

export const client = contentful.createClient({
  accessToken: process.env.CONTENTFUL_ACCESS_TOKEN || "",
  space: process.env.CONTENTFUL_SPACE_ID || "",
});

取得したデータを出力する

src/routes/+page.server.ts
import { client } from '$lib/contentful';

export const load = async () => {
  const posts = await client.getEntries({ content_type: 'post' });
  return {
    posts: posts.items
  };
};

content_type:の部分は適宜Contentfulのモデル名を入れてください。

src/routes/+page.svelte
<script lang="ts">
  export let data: { posts: any[] };
</script>

{#each data.posts as post}
  <article>
    <h1>{post.fields.title}</h1>
    <p>{post.fields.content}</p>
  </article>
{/each}

できた……?

めちゃめちゃ手探りなので引き続き精進します。

参考: https://dev.to/wesleymutwiri/create-a-blog-with-contentful-and-sveltekit-3bd6

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?