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
を作成し、各値を設定する。
.envCONTENTFUL_SPACE_ID= CONTENTFUL_ENVIRONMENT= CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN=
プロジェクトルートにgetContentfulEnvironment.js
を作成する。
getContentfulEnvironment.jsrequire('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も入っていたので、消した 🤢
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, }, }; };