next js 教程: 全面指南和实践

Author

Reads 789

Web banner with online information on computer
Credit: pexels.com, Web banner with online information on computer

Next.js 是一个强大的 React 框架,让我们快速构建高性能的 web 应用。它提供了许多有用的特性,如服务器渲染、静态站点生成和路由管理。

Next.js 支持 TypeScript,允许我们使用类型安全的 JavaScript 编程。我们可以在项目中使用 TypeScript 的强大类型系统,提高代码的可读性和维护性。

在 Next.js 中,我们可以使用 Pages 来组织我们的 React 组件。Pages 是 Next.js 的一个核心概念,它们允许我们定义 URL 路径和组件之间的映射。

A fresh viewpoint: Pages Router Next Js

Next.js 基础

Next.js 是一个强大的框架,用于构建通用 React 应用程序,允许在服务器端渲染模板,使用组件这种我们最常用的前端开发方式。

你可以使用 npm 命令将 Next.js 初始化为一个 Node 项目,生成一个模板文件——package.json。

在 Next.js 中,pages 文件夹是非常重要的,它用于存放应用程序的页面组件。例如,你可以在 pages/blog.js 中列出这些帖子。

Check this out: Nextjs Pages

Jie Shao

Next.js 是一个 React 框架,它可以帮助你解决一些常见的问题。例如,它可以让你的页面加载更快,因为它可以在服务器端渲染,而不是在浏览器端。

Next.js 还提供了一个通用的结构,使你能够轻松地构建一个前端的 React 应用程序,并透明地为你处理服务器端的渲染。它的创造者把它宣传为一个零配置、单指令的 React 应用工具链。

Next.js 有很多强大功能,包括客户端渲染、服务端渲染、静态生成、自动代码分割、客户端路由、CSS 和 Sass 支持等。这些功能使得 Next.js 成为了一个非常强大的 React 框架。

要使用 Next.js,首先你需要安装 Node 和 npm,然后使用 Next.js 提供的命令行工具来创建一个新的 Next.js 项目。Next.js 会自动为你配置好所有的依赖包和文件结构。

Next.js 的路由系统非常简单和易用。例如,你可以使用 Link 组件来创建一个客户端路由。Link 组件可以让你在浏览器端进行导航,而不需要向浏览器发送请求。

Next.js 还支持服务端渲染(SSR),这意味着你可以在服务器端渲染你的页面。SSR 是非常有用的,因为它可以让你的页面加载更快,并且可以更好地支持 SEO。

要使用 SSR,需要在你的页面中使用 getServerSideProps 方法。这方法可以让你在服务器端渲染你的页面,并且可以让你获取请求的所有数据。

在 Next.js 中,getServerSideProps 方法和 getStaticProps 方法不能同时使用。getServerSideProps 方法会对每次请求进行重新渲染,而 getStaticProps 方法会在构建时进行静态生成。

总的来说,Next.js 是一个非常强大的 React 框架,它可以帮助你解决一些常见的问题并且提供了很多强大功能。它的路由系统非常简单和易用,并且支持服务端渲染和静态生成。

Intriguing read: Next Js Getstaticprops

The React Framework

Next.js is the React framework that solves all the problems you'd encounter when building a Next.js application. It provides an intuitive page-based routing system with support for dynamic routes, pre-rendering, automatic code splitting, client-side routing with optimized prefetching, built-in CSS and Sass support, and a development environment with Fast Refresh support.

Next.js is used in tens of thousands of production-facing websites and web applications, including many of the world's largest brands. Its creator aimed to create a zero-configuration, single-command React application toolchain.

Check this out: Next Js React

Close-up of JavaScript code on a laptop screen, showcasing programming in progress.
Credit: pexels.com, Close-up of JavaScript code on a laptop screen, showcasing programming in progress.

Here are some of the key features of Next.js:

  • An intuitive page-based routing system (with support for dynamic routes)
  • Pre-rendering, both static generation (SSG) and server-side rendering (SSR) are supported on a per-page basis
  • Automatic code splitting for faster page loads
  • Client-side routing with optimized prefetching
  • Built-in CSS and Sass support, and support for any CSS-in-JS library
  • Development environment with Fast Refresh support
  • API routes to build API endpoints with Serverless Functions
  • Fully extendable

With Next.js, you can easily create a production-ready Next.js application. It's a powerful tool that can help you and your team build amazing React applications.

Automatic Code Splitting

Automatic Code Splitting is a powerful feature in Next.js that helps improve page load times. It works by automatically splitting your application's code into smaller chunks, only loading the code that's necessary for each page.

Next.js does this by analyzing the imports in your code and bundling them accordingly. For example, if you only import Axios in one page, that page will only include Axios in its bundle.

This means that your first page will load as fast as possible, and only subsequent pages will load the additional JavaScript code. There's an exception to this rule, though - if a frequently used import is used in at least half of the pages on your site, it will be bundled into the main JavaScript file.

Here's a summary of how Automatic Code Splitting works:

  • Next.js analyzes imports in your code
  • Bundles are created based on imports
  • Only necessary code is loaded for each page

This technique can significantly improve page load times, especially for large applications.

Next.js 功能

Next.js 是一个强大的框架,可以帮助你快速构建通用 React 应用程序。它使用 React 在服务器端渲染模板,可以用上组件这种我们最常用的前端开发方式。

Next.js 有许多功能可以帮助你提高开发效率。例如,它可以帮助你做生产优化,如代码分割,静态预渲染页面,服务器端渲染或客户端渲染。这些功能可以帮助你提高页面的性能和 SEO。

一些 Next.js 的功能包括:

  • 代码分割
  • 静态预渲染
  • 服务器端渲染
  • 客户端渲染

Next.js 提供的主要功能

A focused engineer organizing tools in a vibrant workshop setting.
Credit: pexels.com, A focused engineer organizing tools in a vibrant workshop setting.

Next.js 通过解决一些常见问题来帮助开发者。例如,代码需要被打包和转换,生产优化也很重要。通过使用 Next.js,开发者可以让 Next.js 来解决这些问题。

Next.js 支持静态预渲染,这可以提高性能和 SEO。同时,它也支持服务端渲染和客户端渲染。

Next.js 有以下几大功能:

  • 代码打包和转换
  • 生产优化
  • 静态预渲染
  • 服务端渲染和客户端渲染

这些功能可以让开发者专注于编写代码,而不用再担心这些底层问题。

Prefetching (预取)

Prefetching (预取) is a powerful feature in Next.js that helps improve the performance of your application by automatically fetching resources for linked pages in the background.

With the prefetch prop, you can enable prefetching for Link components that connect different pages, ensuring that resources are loaded before the user navigates to them.

Next.js will prefetch any local link that appears in the viewport, making your application super fast for users. This behavior is only triggered in production mode, so make sure to stop your development server and run your production build before testing prefetching.

You can disable prefetching for individual Link instances by setting the prefetch prop to false.

Dynamic Components

Dynamic Components are a powerful feature in Next.js that allows you to render components conditionally.

By using the `getStaticProps` method, you can fetch data at build time and render components based on that data. For example, in the "静态站点生成" section, we saw how to use `getStaticProps` to fetch data from an API and render a list of posts.

Dynamic Components can also be used to render different components based on a user's role or location. In the "路由和动态路由" section, we saw how to use dynamic routes to render different components based on a user's location.

By using Dynamic Components, you can create a more personalized and engaging user experience.

Explore further: Next Js Components

使用 GetInitialProps() 向组件提供数据

Two business professionals brainstorming and planning software development with a whiteboard in an office.
Credit: pexels.com, Two business professionals brainstorming and planning software development with a whiteboard in an office.

GetInitialProps() is a special function that can be used to provide data to components in Next.js. In the previous chapter, we encountered an issue when trying to dynamically generate post pages because the component needed some pre-requisite data. We tried to get the data from a JSON file, but we got an error.

To solve this problem, we need to provide props to the component using the GetInitialProps() function. This function is attached to the component and gets an object as its parameter, which includes several properties. We're interested in the query object, which contains the post ID.

We can use object destructuring to get the query object from the function. Now we can return the post data from this function. We can also delete the useRouter import, as we can get the post data from the props attribute passed to the Post component.

The GetInitialProps() function will be executed on the server-side, but it will also be executed on the client-side when we use the Link component to navigate to a new page. The function receives a context object, which includes the query object, as well as other properties like pathname and asPath.

Here are the properties you can expect to receive in the context object:

  • pathname: The URL path portion
  • asPath: The actual path shown in the browser (including query)

类型支持

如果你熟悉 TypeScript,会发现 Next.js 的类型支持非常方便。

TypeScript Support

Credit: youtube.com, TypeScript 入门 VIP第2课 TypeScript 类型系统介绍

Next.js is built with TypeScript, which means it has excellent TypeScript support. This is evident in its robust type checking and auto-completion features.

Next.js developers can take advantage of TypeScript's static type checking to catch errors early in the development process. This can significantly reduce the number of bugs and make the development process more efficient.

Next.js is written in TypeScript, so its own codebase is a testament to the power of TypeScript. By using TypeScript, Next.js developers can write more maintainable and scalable code.

TypeScript's strong typing system allows Next.js developers to catch type-related errors at compile time, rather than at runtime. This can save a lot of time and effort in the long run.

A different take: Next Js Typescript

Client端通过 UseSession 钩子获取鉴权信息

On the client-side, you can use the `UseSession` hook to get authentication information. This hook allows you to access the user's session data.

You can use the `UseSession` hook in your client-side code to get the user's authentication token. The token is stored in the session object.

To use the `UseSession` hook, you need to import it from the `@auth0/auth0-spa-js` package. The hook returns the session object, which contains the authentication token and other user data.

路由

Credit: youtube.com, 【Next.js 14 系列教程】App路由

我们可以通过在 `pages` 目录下创建一个文件,如 `blog/[id].js`,来创建一个动态的 URL。这个文件将处理 `/blog/` 路径下的所有动态 URL。例如,`/blog/hello-world` 和 `/blog/my-second-post`。

在这个文件中,我们可以使用 `useRouter` 来实例化路由对象,并从中提取信息。例如,我们可以通过访问 `router.query.id` 来获得 `[id].js` 文件中 URL 的动态部分。

为了支持浏览器端导航,我们需要使用 Next.js 提供的 Link 组件。这个组件是通过 `next/link` 导出的。

在 `pages/index.js` 中,我们可以使用 Link 组件来创建一个链接到 `/about` 页面的按钮。

我们可以通过在 `pages` 目录下创建一个文件 `routes.js` 来定义路由器。这个文件应该包含一个 `next-routes` 的实例。

这些是 Next.js 中路由的基本概念。通过使用这些概念,我们可以创建动态的 URL 和支持浏览器端导航的应用程序。

静态文件

静态文件是 Next.js 的一个重要组成部分,它们可以被直接访问而不需要服务器端的渲染。

Next.js 支持使用 public 文件夹来存储静态文件,这个文件夹是可以直接访问的。

在 Next.js 中,静态文件可以通过 URL 来访问,例如通过使用 Link 组件来跳转到静态文件。

Static Exports (静态导出)

Static Exports (静态导出) are a way to build Next.js projects without a Node.js server environment. This method uses the `next export` command to create a static package.

The generated code will only include frontend content, such as HTML, CSS, JS, and static resources. This means you won't have a Node.js server program, which is a significant departure from traditional Next.js builds.

One of the main trade-offs of using Static Exports is that you won't be able to use features like API routes or Server-Side Rendering (SSR) that Next.js provides.

Check this out: Next Js vs Node Js

五、静态文件

这些文件通常存储在服务器的public目录中,通过URL直接访问。例如,一个网页的HTML文件可以通过http://example.com/index.html访问。

静态文件的大小通常很小,平均大小在几KB到几MB之间。对于大型静态文件,服务器可能需要进行缓存来提高访问速度。

部署

生产版本是高度优化的,没有 source maps 和其他诸如 hot code reloading 的东西,这对终端用户没有好处。命令的输出会告诉我们一些路由(如 / 和 /blog)被预设为静态 HTML,而其他路由(如 /blog/[id])将由 Node.js 后端提供。

我们可以通过 Now 平台将应用程序部署到真正的网络服务器上。Now 是一个云平台,支持部署 Node.js 应用程序、静态网站等。它的部署和分发步骤非常简单和快速。

如果我们需要更多的资源,我们可以查看 Now 的定价页。我们还需要注册一个账户并将电子邮件添加到 CLI 客户端。然后,我们可以从 Next.js 项目根目录下运行 now 命令,应用程序将被立即部署到 Now 云中,我们将得到一个独特的应用程序 URL。

这个 URL 将会随机生成,每次我们部署应用程序时都会改变。我们可以通过改变项目代码中的某些内容并再次运行 now 来立即测试。其他两个 URL 将不会改变,第一个是随机的,第二个是我们的项目名称(默认为当前项目文件夹,账户名,然后是 now.sh)。

访问这个 URL,我们会看到应用被部署到生产中。我们可以将 Now 配置为将网站提供给我们自己的自定义域或子域,但这不是本教程的重点。现在,我们可以使用 now.sh 子域来测试我们的应用程序。

Intriguing read: Nextjs Blogs

API

Credit: youtube.com, #1 - Wordpress后端准备 | Next.js + Wordpress REST API 建站教程

API in Next.js is a powerful tool for building server-side logic.

The /pages/api files under the root directory of your project won't export page components, but Next.js will map them to API endpoints at /api/*.

Next.js team has wrapped the NodeJS http module to provide a similar web server development experience as Express.

We can write server-side logic in these files, just like with getStaticProps, and it will be invisible to the client-side.

The basic format of API routes is /pages/index.js.

Thomas Goodwin

Lead Writer

Thomas Goodwin is a seasoned writer with a passion for exploring the intersection of technology and business. With a keen eye for detail and a knack for simplifying complex concepts, he has established himself as a trusted voice in the tech industry. Thomas's writing portfolio spans a range of topics, including Azure Virtual Desktop and Cloud Computing Costs.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.