nishimura.clubnishimura.club

Contentful の Content Type を型定義する

作成日
2021-08-31
更新日
2021-08-31

ドキュメント

インストール

yarn add contentful yarn add -D contentful-management dotenv contentful-typescript-codegen @contentful/rich-text-types
npm install contentful npm install --save-dev dotenv contentful-management contentful-typescript-codegen @contentful/rich-text-types

実装

.envを作成し、各値を設定する。

.env
CONTENTFUL_SPACE_ID= CONTENTFUL_ENVIRONMENT= CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN=

プロジェクトルートにgetContentfulEnvironment.jsを作成する。

getContentfulEnvironment.js
require('dotenv').config(); const contentfulManagement = require('contentful-management'); module.exports = function () { const contentfulClient = contentfulManagement.createClient({ accessToken: process.env.CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN, }); return contentfulClient .getSpace(process.env.CONTENTFUL_SPACE_ID) .then((space) => space.getEnvironment(process.env.CONTENTFUL_ENVIRONMENT)); };

package.jsonのscriptを追記する。

"scripts": { "contentful-typescript-codegen": "contentful-typescript-codegen --output @types/generated/contentful.d.ts" }

実行

yarn contentful-typescript-codegen

実行すると、@types/generated/contentful.d.tsが生成される。

いくつか要らないContent Typeも入っていたので、消した 🤢

使用の一例(Next.js)

import { IArticle, IArticleFields } from '@/@types/generated/contentful'; interface Props { articles: IArticle[]; } export default unction IndexPage({ articles }: Props) { .... } export const getServerSideProps: GetServerSideProps<Props> = async () => { const articles = await client.getEntries({ content_type: 'article' }); return { props: { articles: articles.items, }, }; };

Related

Tags

Contentful
TypeScript
NextJS

Share