Next.js简介

官方介绍: :::tips Next.js 为您提供生产环境所需的所有功能以及最佳的开发体验:包括静态及服务器端融合渲染、 支持 TypeScript、智能化打包、 路由预取等功能 无需任何配置。 :::

用我自己的话来说,Next.js是一个全栈框架,将服务端和客户端有效地统一起来了。

官方GitHub:

创建Next.js应用

使用命令创建Next.js应用:

  1. npx create-next-app@latest
  2. # or
  3. yarn create next-app

项目创建好后,会自动安装依赖,但项目本身不包含目录结构,只有一个packages.json

  1. {
  2. "name": "nextjs_project",
  3. "version": "0.1.0",
  4. "private": true,
  5. "scripts": {
  6. "dev": "next dev",
  7. "build": "next build",
  8. "start": "next start",
  9. "lint": "next lint"
  10. },
  11. "dependencies": {
  12. "next": "12.1.1",
  13. "react": "17.0.2",
  14. "react-dom": "17.0.2"
  15. }
  16. }

运行项目,使用命令:

  1. yarn dev

应用程序默认运行到3000端口下。

如果需要加入git版本控制,请手动在项目下添加 .gitignore文件:

  1. node_modules
  2. .next

构建

使用命令 yarn build进行应用程序构建:

  1. yarn build
  2. yarn run v1.22.17
  3. $ next build
  4. info - Checking validity of types
  5. info - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules
  6. info - Creating an optimized production build
  7. info - Compiled successfully
  8. info - Collecting page data
  9. λ /api/data1 0 B 71.8 kB
  10. /page1 303 B 72.1 kB
  11. /page2 354 B 72.2 kB
  12. /posts/[id] 323 B 72.2 kB
  13. + First Load JS shared by all 71.8 kB
  14. chunks/framework-5f4595e5518b5600.js 42 kB
  15. chunks/main-38102973b285480e.js 27.7 kB
  16. chunks/pages/_app-9a4e0bcfd9f9bf48.js 1.36 kB
  17. chunks/webpack-fd82975a6094609f.js 727 B
  18. λ (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps)
  19. (Static) automatically rendered as static HTML (uses no initial props)
  20. (SSG) automatically generated as static HTML + JSON (uses getStaticProps)
  21. Done in 11.71s.

构建完成后会生成 .next文件夹。

使用命令 yarn start会运行构建好的运用程序。

页面

在项目中创建 pages目录,用于存放React页面代码。

创建页面pages/index.js

  1. function HomePage() {
  2. return <div>home</div>
  3. }
  4. export default HomePage

直接访问 http://localhost:3000/ 就可在浏览器看到效果

路由

动态路由

创建一个动态路由页面,格式为 [queryParam].js

比如创建一个文件 pages/post/[id].js,内容如下:

  1. import { useRouter } from 'next/router'
  2. const Post = () => {
  3. const router = useRouter()
  4. const { id } = router.query
  5. return <p>Post: {id}</p>
  6. }
  7. export default Post

在浏览器中输入 http://localhost:3000/posts/1,可以看到页面中显示:

  1. Post: 1

数据请求