Next.js + TS 从零开始写一个前端导航页面(二、添加 TS 支持)

入不喜欢 typescript ,可以跳过此文章,直接开始撸 js 代码即可。

next 配置 typescript 是很简单的,只需要一次 install 即可。

安装 TS

1
$ npm install --save-dev typescript @types/react @types/node

如果安装失败,那就多来几次,总会成功的。

修改页面

改 ./pages/index.js 为 ./pages/index.tsx ,代码内容不变,还是原来部分:

1
export default () => <div>Welcome to next.js!</div>

重启项目即可

1
2
3
4
5
6
7
8
9
10
11
12
13
$ npm run dev

> jijian.link@1.0.0 dev D:\iwork\www\out\esoji\next
> next

[ wait ] starting the development server ...
[ info ] waiting on http://localhost:3000 ...
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
We detected TypeScript in your project and created a tsconfig.json file for you.

Your tsconfig.json has been populated with default values.

[ info ] bundled successfully, waiting for typecheck results...

项目目录下被默认创建了 tsconfig.json ,可以修改此文件配置出你最喜欢的 TS 环境。

完整的 package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
"name": "jijian.link",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"next": "^9.3.5",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"@types/node": "^13.13.4",
"@types/react": "^16.9.34",
"typescript": "^3.8.3"
}
}
本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-04-27/next-typescript/

如果您觉得文章不错,可以点击文章中的广告支持一下!