跳至内容
Pages 路由器API 参考创建 Next.js 应用

创建 Next.js 应用

使用create-next-app 是开始使用 Next.js 最简单的方法。这个 CLI 工具可以让你快速开始构建一个新的 Next.js 应用,并且为你设置好所有东西。

你可以使用默认的 Next.js 模板创建一个新应用,或者使用 官方 Next.js 示例 中的一个。

交互式

你可以通过运行以下命令来交互式地创建一个新项目

终端
npx create-next-app@latest
终端
yarn create next-app
终端
pnpm create next-app
终端
bunx create-next-app

然后你会被问到以下提示

终端
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 to use `src/` directory?  No / Yes
Would you like to use App Router? (recommended)  No / Yes
Would you like to customize the default import alias (@/*)?  No / Yes

回答完提示后,将根据你的答案创建一个新的项目,并具有正确的配置。

非交互式

你也可以传递命令行参数来非交互式地设置一个新项目。

此外,你可以通过在默认选项前添加--no-来否定它们(例如--no-eslint)。

参见create-next-app --help

终端
Usage: create-next-app <project-directory> [options]
 
Options:
  -V, --version                        output the version number
  --ts, --typescript
 
    Initialize as a TypeScript project. (default)
 
  --js, --javascript
 
    Initialize as a JavaScript project.
 
  --tailwind
 
    Initialize with Tailwind CSS config. (default)
 
  --eslint
 
    Initialize with ESLint config.
 
  --app
 
    Initialize as an App Router project.
 
  --src-dir
 
    Initialize inside a `src/` directory.
 
  --import-alias <alias-to-configure>
 
    Specify import alias to use (default "@/*").
 
  --use-npm
 
    Explicitly tell the CLI to bootstrap the app using npm
 
  --use-pnpm
 
    Explicitly tell the CLI to bootstrap the app using pnpm
 
  --use-yarn
 
    Explicitly tell the CLI to bootstrap the app using Yarn
 
  --use-bun
 
    Explicitly tell the CLI to bootstrap the app using Bun
 
  -e, --example [name]|[github-url]
 
    An example to bootstrap the app with. You can use an example name
    from the official Next.js repo or a public GitHub URL. The URL can use
    any branch and/or subdirectory
 
  --example-path <path-to-example>
 
    In a rare case, your GitHub URL might contain a branch name with
    a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar).
    In this case, you must specify the path to the example separately:
    --example-path foo/bar
 
  --reset-preferences
 
    Explicitly tell the CLI to reset any stored preferences
 
  -h, --help                           output usage information

为什么要使用 Create Next App?

create-next-app 允许你在几秒钟内创建一个新的 Next.js 应用。它由 Next.js 的创建者官方维护,并包含许多优势

  • 交互式体验:运行npx create-next-app@latest(不带参数)会启动一个交互式体验,引导你完成项目的设置。
  • 零依赖:初始化一个项目只需一秒钟。Create Next App 没有依赖项。
  • 离线支持: Create Next App 会自动检测您是否处于离线状态,并使用本地包缓存启动您的项目。
  • 示例支持: Create Next App 可以使用 Next.js 示例集合中的示例(例如 npx create-next-app --example api-routes)或任何公共 GitHub 仓库来启动您的应用程序。
  • 经过测试: 该包是 Next.js 单仓库的一部分,并使用与 Next.js 本身相同的集成测试套件进行测试,确保它在每次发布时都能按预期工作。