Skip to main content

如何设置 Next.js 项目

系统要求

¥System requirements

  • Node.js 18.18 或更高版本。

    ¥Node.js 18.18 or later.

  • 支持 macOS、Windows(包括 WSL)和 Linux。

    ¥macOS, Windows (including WSL), and Linux are supported.

自动安装

¥Automatic installation

我们建议使用 create-next-app 启动一个新的 Next.js 应用,它会自动为你设置所有内容。要创建项目,请运行:

¥We recommend starting a new Next.js app using create-next-app, which sets up everything automatically for you. To create a project, run:

npx create-next-app@latest

安装时,你将看到以下提示:

¥On installation, you'll see the following prompts:

What is your project named? my-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like your code inside a `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to use Turbopack for `next dev`? No / Yes
Would you like to customize the import alias (`@/*` by default)? No / Yes
What import alias would you like configured? @/*

出现提示后,create-next-app 将以你的项目名称创建一个文件夹并安装所需的依赖。

¥After the prompts, create-next-app will create a folder with your project name and install the required dependencies.

手动安装

¥Manual installation

要手动创建新的 Next.js 应用,请安装所需的包:

¥To manually create a new Next.js app, install the required packages:

npm install next@latest react@latest react-dom@latest

打开 package.json 文件并添加以下 scripts

¥Open your package.json file and add the following scripts:

{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
}

这些脚本涉及开发应用的不同阶段:

¥These scripts refer to the different stages of developing an application:

  • dev:运行 next dev 以在开发模式下启动 Next.js。

    ¥dev: runs next dev to start Next.js in development mode.

  • build:运行 next build 来构建用于生产的应用。

    ¥build: runs next build to build the application for production usage.

  • start:运行 next start 来启动 Next.js 生产服务器。

    ¥start: runs next start to start a Next.js production server.

  • lint:运行 next lint 来设置 Next.js 的内置 ESLint 配置。

    ¥lint: runs next lint to set up Next.js' built-in ESLint configuration.

创建 app 目录

¥Create the app directory

Next.js 使用文件系统路由,这意味着应用中的路由由你构建文件的方式决定。

¥Next.js uses file-system routing, which means the routes in your application are determined by how you structure your files.

创建 app 文件夹,然后添加 layout.tsxpage.tsx 文件。当用户访问应用的根目录 (/) 时,将渲染这些内容。

¥Create an app folder, then add a layout.tsx and page.tsx file. These will be rendered when the user visits the root of your application (/).

使用所需的 <html><body> 标签在 app/layout.tsx 内创建 根布局

¥Create a root layout inside app/layout.tsx with the required <html> and <body> tags:

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}

最后,创建一个主页 app/page.tsx,其中包含一些初始内容:

¥Finally, create a home page app/page.tsx with some initial content:

export default function Page() {
return <h1>Hello, Next.js!</h1>
}
export default function Page() {
return <h1>Hello, Next.js!</h1>
}

很高兴知道:

¥Good to know:

  • 如果你忘记创建 layout.tsx,Next.js 将在使用 next dev 运行开发服务器时自动创建此文件。

    ¥If you forget to create layout.tsx, Next.js will automatically create this file when running the development server with next dev.

  • 你可以选择在项目的根目录中使用 src 目录 将应用的代码与配置文件分开。

    ¥You can optionally use a src directory in the root of your project to separate your application's code from configuration files.

创建 public 文件夹(可选)

¥Create the public folder (optional)

你可以选择在项目的根目录创建一个 public 文件夹 来存储静态资源,例如图片、字体等。然后,你的代码可以从基本 URL(/)开始引用 public 中的文件。

¥You can optionally create a public folder at the root of your project to store static assets such as images, fonts, etc. Files inside public can then be referenced by your code starting from the base URL (/).

运行开发服务器

¥Run the development server

  1. 运行 npm run dev 以启动开发服务器。

    ¥Run npm run dev to start the development server.

  2. 访问 http://localhost:3000 查看你的应用。

    ¥Visit http://localhost:3000 to view your application.

  3. 编辑 app/page.tsx 文件并保存以在浏览器中查看更新的结果。

    ¥Edit theapp/page.tsx file and save it to see the updated result in your browser.

设置 TypeScript

¥Set up TypeScript

最低 TypeScript 版本:v4.5.2

¥Minimum TypeScript version: v4.5.2

Next.js 带有内置 TypeScript 支持。要将 TypeScript 添加到你的项目,请将文件重命名为 .ts / .tsx。运行 next dev,Next.js 将自动安装必要的依赖并添加带有推荐配置选项的 tsconfig.json 文件。

¥Next.js comes with built-in TypeScript support. To add TypeScript to your project, rename a file to .ts / .tsx. Run next dev, Next.js will automatically install the necessary dependencies and add a tsconfig.json file with the recommended config options.

很高兴知道:

¥Good to know:

  • 如果你已经有 jsconfig.json 文件,请将 paths 编译器选项从旧的 jsconfig.json 复制到新的 tsconfig.json 文件中,然后删除旧的 jsconfig.json 文件。

    ¥If you already have a jsconfig.json file, copy the paths compiler option from the old jsconfig.json into the new tsconfig.json file, and delete the old jsconfig.json file.

IDE 插件

¥IDE Plugin

Next.js 包含一个自定义 TypeScript 插件和类型检查器,VSCode 和其他代码编辑器可以使用它来进行高级类型检查和自动补齐。

¥Next.js includes a custom TypeScript plugin and type checker, which VSCode and other code editors can use for advanced type-checking and auto-completion.

你可以通过以下方式在 VS Code 中启用该插件:

¥You can enable the plugin in VS Code by:

  1. 打开命令面板(Ctrl/⌘ + Shift + P

    ¥Opening the command palette (Ctrl/⌘ + Shift + P)

  2. 搜索“TypeScript:选择 TypeScript 版本”

    ¥Searching for "TypeScript: Select TypeScript Version"

  3. 选择 "使用工作区版本"

    ¥Selecting "Use Workspace Version"

现在,在编辑文件时,将启用自定义插件。运行 next build 时,将使用自定义类型检查器。

¥Now, when editing files, the custom plugin will be enabled. When running next build, the custom type checker will be used.

有关如何在项目中使用 TypeScript 的更多信息,请参阅 TypeScript 配置 页面。

¥See the TypeScript configuration page for more information on how to use TypeScript in your project.

设置 ESLint

¥Set up ESLint

Next.js 带有内置 ESLint,当你使用 create-next-app 创建新项目时,它会自动安装必要的软件包并配置适当的设置。

¥Next.js comes with built-in ESLint, automatically installing the necessary packages and configuring the proper settings when you create a new project with create-next-app.

要将 ESLint 添加到现有项目,请将 next lint 作为脚本添加到 package.json

¥To add ESLint to an existing project, add next lint as a script to package.json:

{
"scripts": {
"lint": "next lint"
}
}

然后,运行 npm run lint,你将被引导完成安装和配置过程。

¥Then, run npm run lint and you will be guided through the installation and configuration process.

pnpm lint

你会看到这样的提示:

¥You'll see a prompt like this:

? 你希望如何配置 ESLint?

¥? How would you like to configure ESLint?

❯ 严格(推荐)基础取消

¥❯ Strict (recommended)\ Base\ Cancel

  • 严格的:包括 Next.js 的基本 ESLint 配置以及更严格的 Core Web Vitals 规则集。这是首次设置 ESLint 的开发者的推荐配置。

    ¥Strict: Includes Next.js' base ESLint configuration along with a stricter Core Web Vitals rule-set. This is the recommended configuration for developers setting up ESLint for the first time.

  • 根据:包括 Next.js 的基本 ESLint 配置。

    ¥Base: Includes Next.js' base ESLint configuration.

  • 取消:不包括任何 ESLint 配置。仅当你计划设置自己的自定义 ESLint 配置时才选择此选项。

    ¥Cancel: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration.

如果选择这两个配置选项中的任何一个,Next.js 将自动安装 eslinteslint-config-next 作为应用中的依赖,并在项目的根目录中创建一个 .eslintrc.json 文件,其中包含你选择的配置。

¥If either of the two configuration options are selected, Next.js will automatically install eslint and eslint-config-next as dependencies in your application and create an .eslintrc.json file in the root of your project that includes your selected configuration.

现在,你每次想要运行 ESLint 来捕获错误时都可以运行 next lint。一旦 ESLint 设置完毕,它也会在每次构建 (next build) 期间自动运行。错误将使构建失败,而警告则不会。

¥You can now run next lint every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (next build). Errors will fail the build, while warnings will not.

有关如何在项目中配置 ESLint 的更多信息,请参阅 ESLint 插件 页面。

¥See the ESLint Plugin page for more information on how to configure ESLint in your project.

设置绝对导入和模块路径别名

¥Set up Absolute Imports and Module Path Aliases

Next.js 内置支持 tsconfig.jsonjsconfig.json 文件的 "paths""baseUrl" 选项。这些选项允许你将项目目录别名为绝对路径,从而更轻松地导入模块。例如:

¥Next.js has in-built support for the "paths" and "baseUrl" options of tsconfig.json and jsconfig.json files. These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:

// Before
import { Button } from '../../../components/button'

// After
import { Button } from '@/components/button'

要配置绝对导入,请将 baseUrl 配置选项添加到你的 tsconfig.jsonjsconfig.json 文件中。例如:

¥To configure absolute imports, add the baseUrl configuration option to your tsconfig.json or jsconfig.json file. For example:

{
"compilerOptions": {
"baseUrl": "src/"
}
}

除了配置 baseUrl 路径之外,你还可以使用 "paths" 选项来配置 "alias" 模块路径。

¥In addition to configuring the baseUrl path, you can use the "paths" option to "alias" module paths.

例如,以下配置将 @/components/* 映射到 components/*

¥For example, the following configuration maps @/components/* to components/*:

{
"compilerOptions": {
"baseUrl": "src/",
"paths": {
"@/styles/*": ["styles/*"],
"@/components/*": ["components/*"]
}
}
}

每个 "paths" 都相对于 baseUrl 位置。例如:

¥Each of the "paths" are relative to the baseUrl location. For example:

import Button from '@/components/button'
import '@/styles/styles.css'

export default function HomePage() {
return (
<div>
<h1>Hello World</h1>
<Button />
</div>
)
}
import Button from '@/components/button'
import '@/styles/styles.css'

export default function HomePage() {
return (
<div>
<h1>Hello World</h1>
<Button />
</div>
)
}