Unverified Commit 0d5a692d authored by Shawn Callegari's avatar Shawn Callegari Committed by GitHub

Port 'with-static-export' example to TypeScript (#38268)

The 'with-static-export' example is very useful but, if a developer wants to use TypeScript, converting it is nontrivial. There are some gotchas in the GetStaticProps/GetStaticPaths functions. This example should help jumpstart TS development for sites static generation.

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent 32383521
import Link from 'next/link' import Link from 'next/link'
import { PostData } from '../types/postdata'
export default function Post({ title, body, id }) { export default function Post({ title, body, id }: PostData) {
return ( return (
<article> <article>
<h2>{title}</h2> <h2>{title}</h2>
......
import { PostData } from '../types/postdata'
export async function GetPost(id: string): Promise<PostData> {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
)
const postData: PostData = (await response.json()) as PostData
return postData
}
export async function GetPosts(): Promise<PostData[]> {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts?_page=1'
)
const postList: PostData[] = (await response.json()) as PostData[]
return postList
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
{ {
"private": true, "private": true,
"dependencies": {
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"serve": "11.2.0"
},
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
"preexport": "npm run build", "preexport": "npm run build",
"export": "next export", "export": "next export",
"prestart": "npm run export", "prestart": "npm run export",
"start": "serve out" "start": "serve out",
"lint": "next lint"
},
"dependencies": {
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"serve": "^14.0.1"
},
"devDependencies": {
"@types/node": "^18.0.0",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"eslint": "8.19.0",
"eslint-config-next": "12.2.0",
"typescript": "^4.7.4"
} }
} }
import Head from 'next/head' import Head from 'next/head'
import { GetStaticProps, NextPage } from 'next'
import Post from '../components/post' import Post from '../components/post'
import { PostData, PostDataListProps } from '../types/postdata'
import { GetPosts } from '../lib/postdata_api'
export async function getStaticProps() { export const getStaticProps: GetStaticProps = async (_context) => {
// fetch list of posts // fetch list of posts
const response = await fetch( const posts: PostData[] = await GetPosts()
'https://jsonplaceholder.typicode.com/posts?_page=1'
)
const postList = await response.json()
return { return {
props: { props: {
postList, postDataList: posts,
}, },
} }
} }
export default function IndexPage({ postList }) { const IndexPage: NextPage<PostDataListProps> = ({
postDataList,
}: PostDataListProps) => {
return ( return (
<main> <main>
<Head> <Head>
...@@ -25,10 +26,12 @@ export default function IndexPage({ postList }) { ...@@ -25,10 +26,12 @@ export default function IndexPage({ postList }) {
<h1>List of posts</h1> <h1>List of posts</h1>
<section> <section>
{postList.map((post) => ( {postDataList.map((post: PostData) => (
<Post {...post} key={post.id} /> <Post {...post} key={post.id} />
))} ))}
</section> </section>
</main> </main>
) )
} }
export default IndexPage
import Link from 'next/link'
import Head from 'next/head'
export async function getStaticPaths() {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts?_page=1'
)
const postList = await response.json()
return {
paths: postList.map((post) => {
return {
params: {
id: `${post.id}`,
},
}
}),
fallback: false,
}
}
export async function getStaticProps({ params }) {
// fetch single post detail
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${params.id}`
)
const post = await response.json()
return {
props: post,
}
}
export default function Post({ title, body }) {
return (
<main>
<Head>
<title>{title}</title>
</Head>
<h1>{title}</h1>
<p>{body}</p>
<Link href="/">
<a>Go back to home</a>
</Link>
</main>
)
}
import Link from 'next/link'
import Head from 'next/head'
import React from 'react'
import { GetStaticProps, GetStaticPaths, NextPage } from 'next'
import { ParsedUrlQuery } from 'querystring'
import { PostData, PostDataProps } from '../../types/postdata'
import { GetPosts, GetPost } from '../../lib/postdata_api'
interface Params extends ParsedUrlQuery {
id: string
}
export const getStaticPaths: GetStaticPaths<Params> = async () => {
const postList: PostData[] = await GetPosts()
return {
paths: postList.map((post) => {
return {
params: {
id: post.id.toString(),
},
}
}),
fallback: false,
}
}
export const getStaticProps: GetStaticProps<PostDataProps, Params> = async (
context
) => {
const { id } = context.params! as Params
const postData: PostData = await GetPost(id)
return {
props: {
postData,
},
}
}
const Post: NextPage<PostDataProps> = ({ postData }: PostDataProps) => {
return (
<main>
<Head>
<title>{postData.title}</title>
</Head>
<h1>{postData.title}</h1>
<p>{postData.body}</p>
<Link href="/">
<a>Go back to home</a>
</Link>
</main>
)
}
export default Post
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"moduleResolution": "node"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
export interface PostData {
userId: number
id: number
title: string
body: string
}
export interface PostDataProps {
postData: PostData
}
export interface PostDataListProps {
postDataList: PostData[]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment