Spec-Zone.ru › Next.js

Next.js CLI

Next.js CLI позволяет разрабатывать, собирать, запускать ваше приложение и многое другое.

Чтобы получить список доступных команд CLI, выполните следующую команду в каталоге вашего проекта:

next -h

Вывод должен выглядеть так:

Usage next [options] [command]
 
The Next.js CLI allows you to develop, build, start your application, and more.
 
Options:
  -v, --version                Outputs the Next.js version.
  -h, --help                   Displays this message.
 
Commands:
  build [directory] [options]  Creates an optimized production build of your application.
                               The output displays information about each route.
  dev [directory] [options]    Starts Next.js in development mode with hot-code reloading,
                               error reporting, and more.
  info [options]               Prints relevant details about the current system which can be
                               used to report Next.js bugs.
  lint [directory] [options]   Runs ESLint for all files in the `/src`, `/app`, `/pages`,
                               `/components`, and `/lib` directories. It also provides a
                               guided setup to install any required dependencies if ESLint
                               is not already configured in your application.
  start [directory] [options]  Starts Next.js in production mode. The application should be
                               compiled with `next build` first.
  telemetry [options]          Allows you to enable or disable Next.js' completely
                               anonymous telemetry collection.

Вы можете передать любые аргументы Node командам next.

NODE_OPTIONS='--throw-deprecation' next
NODE_OPTIONS='-r esm' next
NODE_OPTIONS='--inspect' next

Важно знать: Запуск next без команды эквивалентен запуску next dev

Разработка

next dev запускает приложение в режиме разработки с горячей перезагрузкой, отслеживанием ошибок и прочим.

Чтобы получить список доступных параметров с next dev, выполните следующую команду в каталоге вашего проекта:

next dev -h

Вывод должен выглядеть так:

Usage: next dev [directory] [options]
 
Starts Next.js in development mode with hot-code reloading, error reporting, and more.
 
Arguments:
  [directory]                              A directory on which to build the application.
                                           If no directory is provided, the current
                                           directory will be used.
 
Options:
  --turbo                                  Starts development mode using Turbopack (beta).
  -p, --port <port>                        Specify a port number on which to start the
                                           application. (default: 3000, env: PORT)
  -H, --hostname <hostname>                Specify a hostname on which to start the
                                           application (default: 0.0.0.0).
  --experimental-https                     Starts the server with HTTPS and generates a
                                           self-signed certificate.
  --experimental-https-key, <path>         Path to a HTTPS key file.
  --experimental-https-cert, <path>        Path to a HTTPS certificate file.
  --experimental-https-ca, <path>          Path to a HTTPS certificate authority file.
  --experimental-upload-trace, <traceUrl>  Reports a subset of the debugging trace to a
                                           remote HTTP URL. Includes sensitive data.
  -h, --help                               Displays this message.

Приложение будет запускаться по умолчанию на http://localhost:3000. Порт по умолчанию можно изменить с помощью -p, как показано ниже:

next dev -p 4000

Или используя переменную окружения PORT.

PORT=4000 next dev

Важно знать:

  • PORT нельзя задавать в .env, так как запуск HTTP-сервера происходит до инициализации любого другого кода.
  • Next.js будет автоматически перепробовать другой порт, пока порт не станет доступным, если порт не указан с помощью параметра CLI --port или переменной окружения PORT.

Вы также можете установить имя хоста, отличное от значения по умолчанию 0.0.0.0, что может быть полезно для обеспечения доступности приложения для других устройств в сети. Значение хоста по умолчанию можно изменить с помощью -H, как показано ниже:

next dev -H 192.168.1.2

Turbopack

Turbopack (бета-версия), наш новый бандлер, который тестируется и стабилизируется в Next.js, помогает ускорить локальные итерации при работе с вашим приложением.

Чтобы использовать Turbopack в режиме разработки, добавьте параметр --turbo:

next dev --turbo

HTTPS для локального разработки

В некоторых случаях, таких как веб-хуки или аутентификация, может потребоваться использовать HTTPS для обеспечения защищенной среды в localhost. Next.js может сгенерировать самозаверяющий сертификат с помощью next dev следующим образом:

next dev --experimental-https

Вы также можете предоставить пользовательский сертификат и ключ с помощью --experimental-https-key и --experimental-https-cert. Дополнительно, вы можете предоставить пользовательский сертификат CA с помощью --experimental-https-ca.

next dev --experimental-https --experimental-https-key ./certificates/localhost-key.pem --experimental-https-cert ./certificates/localhost.pem

next dev --experimental-https предназначен только для разработки и создает локально доверенный сертификат с mkcert. В продакшене используйте правильно выпущенные сертификаты от доверенных авторитетов. При развертывании на Vercel HTTPS автоматически настраивается для вашего приложения Next.js.

Сборка

next build создаёт оптимизированную сборку приложения для продакшена. Вывод отображает информацию о каждом маршруте:

Route (app)                               Size     First Load JS
┌ ○ /                                     5.3 kB         89.5 kB
├ ○ /_not-found                           885 B          85.1 kB
└ ○ /about                                137 B          84.4 kB
+ First Load JS shared by all             84.2 kB
  ├ chunks/184-d3bb186aac44da98.js        28.9 kB
  ├ chunks/30b509c0-f3503c24f98f3936.js   53.4 kB
  └ other shared chunks (total)
 
 
○  (Static)  prerendered as static content
  • Размер: Количество загружаемых ресурсов при переходе на страницу с клиента. Размер каждого маршрута включает только его зависимости.
  • Первый запрос JS: Количество загружаемых ресурсов при посещении страницы с сервера. Объем JS, используемый всеми, отображается как отдельный показатель.

Оба эти значения сжаты с помощью gzip. Первый запрос отображается зелёным, жёлтым или красным цветом. Стремитесь к зелёному значению для эффективных приложений.

Чтобы получить список доступных опций с next build, выполните следующую команду в каталоге вашего проекта:

next build -h

Вывод должен выглядеть так:

Usage: next build [directory] [options]
 
Creates an optimized production build of your application. The output displays information
about each route.
 
Arguments:
  [directory]                       A directory on which to build the application. If no
                                    provided, the current directory will be
                                    used.
 
Options:
  -d, --debug                       Enables a more verbose build output.
  --profile                         Enables production profiling for React.
  --no-lint                         Disables linting.
  --no-mangling                     Disables mangling.
  --experimental-app-only           Builds only App Router routes.
  --experimental-build-mode [mode]  Uses an experimental build mode. (choices: "compile"
                                    "generate", default: "default")
  -h, --help                        Displays this message.

Отладка

Вы можете включить более подробный вывод сборки с флагом --debug в next build.

next build --debug

При включенном флаге будет отображаться дополнительный вывод сборки, включая переопределения, перенаправления и заголовки.

Проверка кода

Вы можете отключить проверку кода для сборок следующим образом:

next build --no-lint

Искажение имен

Вы можете отключить искажение имен для сборок следующим образом:

next build --no-mangling

Важно знать: Это может повлиять на производительность и должно использоваться только в отладочных целях.

Профилирование

Вы можете включить профилирование продакшена для React с флагом --profile в next build.

next build --profile

После этого вы можете использовать профайлер так же, как и в режиме разработки.

Продакшен

next start запускает приложение в режиме продакшена. Приложение должно быть скомпилировано с помощью next build в первую очередь.

Чтобы получить список доступных параметров с next start, выполните следующую команду в каталоге вашего проекта:

next start -h

Вывод должен выглядеть так:

Usage: next start [directory] [options]
 
Starts Next.js in production mode. The application should be compiled with `next build`
first.
 
Arguments:
  [directory]                           A directory on which to start the application.
                                        If not directory is provided, the current
                                        directory will be used.
 
Options:
  -p, --port <port>                     Specify a port number on which to start the
                                        application. (default: 3000, env: PORT)
  -H, --hostname <hostname>             Specify a hostname on which to start the
                                        application (default: 0.0.0.0).
  --keepAliveTimeout <keepAliveTimeout> Specify the maximum amount of milliseconds to wait
                                        before closing the inactive connections.
  -h, --help                            Displays this message.

Приложение будет запускаться по умолчанию на http://localhost:3000. Порт по умолчанию можно изменить с помощью -p, как показано ниже:

next start -p 4000

Или используя переменную окружения PORT:

PORT=4000 next start

Важно знать:

  • PORT нельзя задавать в .env как запуск HTTP сервера происходит до инициализации любого другого кода.
  • next start нельзя использовать с output: 'standalone' или output: 'export'.

Таймаут Keep-Alive

При развертывании Next.js за прокси-сервером (например, балансировщиком нагрузки, таким как AWS ELB/ALB) важно настроить таймауты Keep-Alive базового HTTP-сервера Next.js, которые больше, чем таймауты прокси-сервера. В противном случае, после достижения таймаута Keep-Alive для определенного TCP-соединения, Node.js немедленно разорвет это соединение, не уведомляя прокси-сервер. Это приводит к ошибке прокси при попытке повторного использования соединения, которое Node.js уже разорвал.

Для настройки значений таймаута для сервера Next.js в продакшене передайте значение --keepAliveTimeout (в миллисекундах) параметру next start, как показано ниже:

next start --keepAliveTimeout 70000

Информация

next info выводит подробную информацию о текущей системе, которая может быть использована для сообщения об ошибках Next.js. Эта информация включает платформу/архитектуру/версию операционной системы, бинарные файлы (Node.js, npm, Yarn, pnpm) и версии пакетов npm (next, react, react-dom).

Чтобы получить список доступных параметров с next info, выполните следующую команду в каталоге вашего проекта:

next info -h

Вывод должен выглядеть следующим образом:

Usage: next info [options]
 
Prints relevant details about the current system which can be used to report Next.js bugs.
 
Options:
  --verbose   Collections additional information for debugging.
  -h, --help  Displays this message.

Запуск next info предоставит информацию, аналогичную этому примеру:

 
Operating System:
  Platform: linux
  Arch: x64
  Version: #22-Ubuntu SMP Fri Nov 5 13:21:36 UTC 2021
  Available memory (MB): 31795
  Available CPU cores: 16
Binaries:
  Node: 16.13.0
  npm: 8.1.0
  Yarn: 1.22.17
  pnpm: 6.24.2
Relevant Packages:
  next: 14.1.1-canary.61 // Latest available version is detected (14.1.1-canary.61).
  react: 18.2.0
  react-dom: 18.2.0
Next.js Config:
  output: N/A
 

Эта информация должна быть вставлена в GitHub Issues.

Вы также можете запустить next info --verbose, который выведет дополнительную информацию о системе и установке пакетов, связанных с next.

Проверка кода

next lint запускает ESLint для всех файлов в каталогах pages/, app/, components/, lib/, и src/. Он также предоставляет руководство по установке необходимых зависимостей, если ESLint ещё не настроен в вашем приложении.

Чтобы получить список доступных опций с next lint, выполните следующую команду в каталоге вашего проекта:

next lint -h

Вывод должен быть таким:

Usage: next lint [directory] [options]
 
Runs ESLint for all files in the `/src`, `/app`, `/pages`, `/components`, and `/lib` directories. It also
provides a guided setup to install any required dependencies if ESLint is not already configured in your
application.
 
Arguments:
  [directory]                                         A base directory on which to lint the application.
                                                      If no directory is provided, the current directory
                                                      will be used.
 
Options:
  -d, --dir, <dirs...>                                Include directory, or directories, to run ESLint.
  --file, <files...>                                  Include file, or files, to run ESLint.
  --ext, [exts...]                                    Specify JavaScript file extensions. (default:
                                                      [".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx"])
  -c, --config, <config>                              Uses this configuration file, overriding all other
                                                      configuration options.
  --resolve-plugins-relative-to, <rprt>               Specify a directory where plugins should be resolved
                                                      from.
  --strict                                            Creates a `.eslintrc.json` file using the Next.js
                                                      strict configuration.
  --rulesdir, <rulesdir...>                           Uses additional rules from this directory(s).
  --fix                                               Automatically fix linting issues.
  --fix-type <fixType>                                Specify the types of fixes to apply (e.g., problem,
                                                      suggestion, layout).
  --ignore-path <path>                                Specify a file to ignore.
  --no-ignore <path>                                  Disables the `--ignore-path` option.
  --quiet                                             Reports errors only.
  --max-warnings [maxWarnings]                        Specify the number of warnings before triggering a
                                                      non-zero exit code. (default: -1)
  -o, --output-file, <outputFile>                     Specify a file to write report to.
  -f, --format, <format>                              Uses a specifc output format.
  --no-inline-config                                  Prevents comments from changing config or rules.
  --report-unused-disable-directives-severity <level> Specify severity level for unused eslint-disable
                                                      directives. (choices: "error", "off", "warn")
  --no-cache                                          Disables caching.
  --cache-location, <cacheLocation>                   Specify a location for cache.
  --cache-strategy, [cacheStrategy]                   Specify a strategy to use for detecting changed files
                                                      in the cache. (default: "metadata")
  --error-on-unmatched-pattern                        Reports errors when any file patterns are unmatched.
  -h, --help                                          Displays this message.

Если вы хотите проверить другие директории, вы можете указать их с помощью флага --dir.

next lint --dir utils

Для получения дополнительной информации об остальных параметрах, ознакомьтесь с нашей документацией по конфигурации ESLint.

Телеметрия

Next.js собирает полностью анонимные данные телеметрии о общем использовании. Участие в этой анонимной программе добровольное, и вы можете отказаться от неё, если не хотите делиться какой-либо информацией.

Чтобы получить список доступных параметров с next telemetry, выполните следующую команду в каталоге вашего проекта:

next telemetry -h

Вывод должен быть таким:

Usage: next telemetry [options]
 
Allows you to enable or disable Next.js' completely anonymous telemetry collection.
 
Options:
  --enable    Eanbles Next.js' telemetry collection.
  --disable   Disables Next.js' telemetry collection.
  -h, --help  Displays this message.
 
Learn more: https://nextjs.org/telemetry

Узнайте больше о Телеметрии.

© 2024 Vercel, Inc.
Licensed under the MIT License.
https://nextjs.org/docs/app/api-reference/next-cli

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API