Next.js教程基本特性:TypeScript

先看个实例:TypeScript

看完后,往下走起。

Next.js 提供了集成的 TypeScript 开发体验,并且开箱即用,类似一个 IDE。

首先,在项目的根目录中创建一个空的 tsconfig.json 文件:

touch tsconfig.json

Next.js 将自动用默认值填充该文件。你还可以在 tsconfig.json 中自定义 编译器参数 。

Next.js 使用 Babel 来处理 TypeScript,因此有一些 需要注意的事项 和一些 对编译器参数处理上的不同

然后,运行 next (通常是 npm run dev 或 yarn dev),Next.js 将引导你完成所需软件包的安装以及设置:

npm run dev

# You'll see instructions like these:
#
# Please install typescript, @types/react, and @types/node by running:
#
#         yarn add --dev typescript @types/react @types/node
#
# ...

现在你就可以将文件从 .js 转换为 .tsx 并且充分利用 TypeScript 所带来的好处了!

在项目的根目录下将创建一个名为 next-env.d.ts 的文件。此文件确保 TypeScript 编译器选择 Next.js 的类型。你不能删除它,但是,你可以对其进行编辑(实际并不需要)。

默认情况下,TypeScript 的 strict 模式是关闭的。如果你对 TypeScript 觉得适应,建议在 tsconfig.json 中将其开启。

默认情况下,Next.js 将在 next build 阶段进行类型检查。我们建议你在开发过程中使用代码编辑器的类型检查功能。

如果要关闭错误报告,请参考文档 忽略 TypeScript 报错。

静态生成和服务器端渲染

对于 getStaticPropsgetStaticPaths 和 getServerSideProps,你可以分别使用 GetStaticPropsGetStaticPaths 和 GetServerSideProps 类型:

import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'

export const getStaticProps: GetStaticProps = async (context) => {
  // ...
}

export const getStaticPaths: GetStaticPaths = async () => {
  // ...
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  // ...
}

如果你使用的是 getInitialProps,则可以 参考相关说明。

API 路由

以下是 API 路由如何使用内置类型的示例:

import type { NextApiRequest, NextApiResponse } from 'next'

export default (req: NextApiRequest, res: NextApiResponse) => {
  res.status(200).json({ name: 'John Doe' })
}

你还可以指定响应数据的类型:

import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default (req: NextApiRequest, res: NextApiResponse) => {
  res.status(200).json({ name: 'John Doe' })
}

自定义 App

如果你 自定义了 App,你可以使用内置类型 AppProps 并将文件名更改为 ./pages/_app.tsx,如下所示:

// import App from "next/app";
import type { AppProps /*, AppContext */ } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext: AppContext) => {
//   // calls page's `getInitialProps` and fills `appProps.pageProps`
//   const appProps = await App.getInitialProps(appContext);

//   return { ...appProps }
// }

export default MyApp

路径别名和 baseUrl

Next.js 自动支持 tsconfig.json 的 "paths" 和 "baseUrl" 参数。

作者:terry,如若转载,请注明出处:https://www.web176.com/nextjs/2471.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年4月20日 下午5:02
下一篇 2021年4月21日 上午11:08

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注