Next.js - CLI
Next.js - 命令行界面 (CLI)
Section titled “Next.js - 命令行界面 (CLI)”Next.js 提供了一个强大的命令行界面 (CLI),可以通过 next 命令访问。它用于初始化、开发、构建和提供(运行)您的 Next.js 应用。
您通常通过 package.json 中定义的 npm 脚本(例如 npm run dev、npm run build)或直接使用 npx next <command> 与 CLI 交互。
要查看可用命令列表和一般帮助:
npx next -h# 或npm run next -- -h要获取特定命令(例如 build)的帮助:
npx next build -hnext dev
Section titled “next dev”启动 Next.js 开发服务器,支持热代码重载、错误报告等功能。
# 通常通过 npm 脚本运行npm run dev
# 或者直接运行npx next dev选项:
-p <端口号>: 指定端口号(例如npx next dev -p 4000)。默认端口是 3000。-H <主机名>: 指定主机名(例如npx next dev -H 0.0.0.0使其可在您的网络上访问)。
next build
Section titled “next build”创建您的应用的优化生产构建。这会编译代码、打包资源、优化图片、预渲染静态页面,并准备无服务器函数。
# 通常通过 npm 脚本运行npm run build
# 或者直接运行npx next build输出文件会放在 .next 目录中。构建输出提供了页面大小和渲染模式(静态 Static、服务器端渲染 Server-Side Rendered (SSR) 、增量静态再生 Incremental Static Regeneration (ISR))的详细信息。
# 构建输出示例片段npm run build
> my-app@0.1.0 build> next build
▲ Next.js 14.x.x - Environments: .env.local - Linting and checking validity of types - Collecting page data... - Generating static pages (0/5) ... - Generating server components (5/5) ... - Compiling Route Handlers (1/1) ... - Generating static pages (5/5)
路由 (app) 大小 首次加载 JS┌ ● / 1.2 kB 85.1 kB├ ● /about 833 B 84.7 kB├ ● /config-demo 1.14 kB 87.1 kB├ ● /posts 787 B 84.6 kB└ ● /posts/[slug] 1.1 kB 85 kB+ First Load JS shared by all 83.9 kB ├ chunks/framework-....js 45.1 kB ├ chunks/main-....js 29.1 kB ├ chunks/pages/_app-....js 0 B ├ chunks/webpack-....js 1.6 kB └ css/....css 8.17 kB
路由 (api) 大小 首次加载 JS● /api/hello 0 B 83.9 kB● /api/users 0 B 83.9 kB
(●) 静态页面)next start
Section titled “next start”在运行 next build 之后,启动 Next.js 生产服务器。这用于提供优化后的应用。
# 通常通过 npm 脚本运行npm run start
# 或者直接运行npx next start选项:
-p <端口号>: 指定端口号(例如npx next start -p 8080)。默认端口是 3000。
next lint
Section titled “next lint”运行为 Next.js 配置的 ESLint 检查,以查找潜在问题并强制执行编码规范。
# 通常通过 npm 脚本运行npm run lint
# 或者直接运行npx next lint虽然 create-next-app 本身不是 next CLI 的一部分,但它是搭建新 Next.js 项目的标准工具:
npx create-next-app@latest my-new-project这会设置项目结构、必要的依赖项和基本配置文件。