配置


¥Config

Read more in Guide > Configuration.

常规

¥General

preset

使用 preset 选项 NITRO_PRESET 环境变量进行自定义生产预设。

¥Use preset option NITRO_PRESET environment variable for custom production preset.

开发模式的预设始终为 nitro_dev,而构建独立 Node.js 服务器的生产环境则默认为 node_server

¥Preset for development mode is always nitro_dev and default node_server for production building a standalone Node.js server.

当未设置 preset 选项且在已知环境中运行时,将自动检测此预设。

¥The preset will automatically be detected when the preset option is not set and running in known environments.

logLevel

  • 默认值:3 lang=ts} (检测到测试环境时为 1

日志详细级别。有关更多信息,请参阅 unjs/consola

¥Log verbosity level. See unjs/consola for more information.

runtimeConfig

  • 默认值:{ nitro: { ... }, ...yourOptions } lang=ts}

服务器运行时配置。

¥Server runtime configuration.

注意:nitro 命名空间已保留。

¥Note:: nitro namespace is reserved.

compatibilityDate

部署提供商引入了 Nitro 预设可以利用的新功能,但其中一些功能需要明确启用。

¥Deployment providers introduce new features that Nitro presets can leverage, but some of them need to be explicitly opted into.

将其设置为 YY-MM-DD 格式的最新测试日期,以利用最新的预设功能。

¥Set it to latest tested date in YY-MM-DD format to leverage latest preset features.

如果未提供此配置,Nitro 将继续使用当前版本 (v2.9) 的预设行为并显示警告。

¥If this configuration is not provided, Nitro will continue using the current (v2.9) behavior for presets and show a warning.

功能

¥Features

experimental

  • 默认值:{}

启用实验性功能。

¥Enable experimental features.

openAPI

启用 /_scalar/_swagger/_openapi.json 端点。

¥Enable /_scalar, /_swagger and /_openapi.json endpoints.

  • 默认值:false

要在路由上定义 OpenAPI 规范,请查看 defineRouteMeta

¥To define the OpenAPI specification on your routes, take a look at defineRouteMeta

你可以在根级别传递一个对象来修改你的 OpenAPI 规范:

¥You can pass an object on the root level to modify your OpenAPI specification:

openAPI: {
  meta: {
    title: 'My Awesome Project',
    description: 'This might become the next big thing.',
    version: '1.0'
  }
}

这些路由在生产环境中默认处于禁用状态。要启用它们,请使用 production 键。"runtime" 允许使用中间件,而 "prerender" 效率最高,因为 JSON 响应是常量。

¥Theses routes are disabled by default in production. To enable them, use the production key. "runtime" allows middleware usage, and "prerender" is the most efficient because the JSON response is constant.

openAPI: {
    // IMPORTANT: make sure to protect OpenAPI routes if necessary!
    production: "runtime", // or "prerender"
}

如果你想自定义 Scalar 集成,可以像这样运行 传递配置对象

¥If you like to customize the Scalar integration, you can pass a configuration object like this:

openAPI: {
  ui: {
    scalar: {
      theme: 'purple'
    }
  }
}

或者,如果你想自定义端点:

¥Or if you want to customize the endpoints:

openAPI: {
  route: "/_docs/openapi.json",
  ui: {
    scalar: {
      route: "/_docs/scalar"
    },
    swagger: {
      route: "/_docs/swagger"
    }
  }
}

wasm

启用 WASM 支持

¥Enable WASM support

legacyExternals

启用后,将使用旧版(不稳定)实验性汇总外部算法。

¥When enabled, legacy (unstable) experimental rollup externals algorithm will be used.

future

  • 默认值:{}

新功能待发布主版本,以避免重大更改。

¥New features pending for a major version to avoid breaking changes.

nativeSWR

使用内置的 SWR 功能(使用缓存层和存储)来实现 Netlify 和 Vercel 预设,而不是回退到 ISR 行为。

¥Uses built-in SWR functionality (using caching layer and storage) for Netlify and Vercel presets instead of falling back to ISR behavior.

storage

  • 默认值:{}

存储配置,更多信息请参阅 存储层 部分。

¥Storage configuration, read more in the Storage Layer section.

timing

  • 默认值:false lang=ts}

启用时间信息:

¥Enable timing information:

  • Nitro 启动时间日志
  • HTTP 响应中的 Server-Timing 标头

renderer

主渲染路径(文件应默认导出事件处理程序)

¥Path to main render (file should export an event handler as default)

serveStatic

  • 输入:boolean | 'node' | 'deno'
  • 默认值:取决于所使用的部署预设。

在生产环境中提供 public/ 资源。

¥Serve public/ assets in production.

注意:强烈建议你的边缘 CDN(Nginx、Apache、Cloud)服务于 .output/public/ 目录,而不是启用压缩和更高级别的缓存。

¥Note: It is highly recommended that your edge CDN (Nginx, Apache, Cloud) serves the .output/public/ directory instead of enabling compression and higher lever caching.

noPublicDir

  • 默认值:false lang=ts}

如果启用,则禁用 .output/public 目录的创建。跳过复制 public/ 目录并禁用预渲染。

¥If enabled, disabled .output/public directory creation. Skipping to copy public/ dir and also disables pre-rendering.

publicAssets

用于在开发环境中提供服务并在生产环境中打包的公共资源目录。

¥Public asset directories to serve in development and bundle in production.

如果检测到 public/ 目录,则会默认添加该目录,但你也可以自行添加更多目录!

¥If a public/ directory is detected, it will be added by default, but you can add more by yourself too!

可以使用 maxAge 选项为资源设置 Cache-Control 标头:

¥It's possible to set Cache-Control headers for assets using the maxAge option:

  publicAssets: [
    {
      baseURL: "images",
      dir: "public/images",
      maxAge: 60 * 60 * 24 * 7, // 7 days
    },
  ],

上述配置会在 public/images/ 文件夹下的资源文件中生成以下标头:

¥The config above generates the following header in the assets under public/images/ folder:

cache-control: public, max-age=604800, immutable

dir 选项是你的文件在文件系统上的存放位置;baseURL 选项是它们在服务/打包时可从哪个文件夹访问。

¥The dir option is where your files live on your file system; the baseURL option is the folder they will be accessible from when served/bundled.

compressPublicAssets

  • 默认值:{ gzip: false, brotli: false } lang=ts}

如果启用,Nitro 会将受支持类型的公共资源和大于 1024 字节的预渲染路由生成预压缩(gzip 和/或 brotli)版本到公共目录中。将使用最佳压缩级别。使用此选项,你可以支持零开销资源压缩,而无需使用 CDN。

¥If enabled, Nitro will generate a pre-compressed (gzip and/or brotli) version of supported types of public assets and prerendered routes larger than 1024 bytes into the public directory. The best compression level is used. Using this option you can support zero overhead asset compression without using a CDN.

可压缩 MIME 类型列表:

¥List of compressible MIME types:

  • application/dash+xml
  • application/eot
  • application/font
  • application/font-sfnt
  • application/javascript
  • application/json
  • application/opentype
  • application/otf
  • application/pdf
  • application/pkcs7-mime
  • application/protobuf
  • application/rss+xml
  • application/truetype
  • application/ttf
  • application/vnd.apple.mpegurl
  • application/vnd.mapbox-vector-tile
  • application/vnd.ms-fontobject
  • application/wasm
  • application/xhtml+xml
  • application/xml
  • application/x-font-opentype
  • application/x-font-truetype
  • application/x-font-ttf
  • application/x-httpd-cgi
  • application/x-javascript
  • application/x-mpegurl
  • application/x-opentype
  • application/x-otf
  • application/x-perl
  • application/x-ttf
  • font/eot
  • font/opentype
  • font/otf
  • font/ttf
  • image/svg+xml
  • text/css
  • text/csv
  • text/html
  • text/javascript
  • text/js
  • text/plain
  • text/richtext
  • text/tab-separated-values
  • text/xml
  • text/x-component
  • text/x-java-source
  • text/x-script
  • vnd.apple.mpegurl

serverAssets

资源可以在服务器逻辑中访问,并在生产环境中打包。阅读更多

¥Assets can be accessed in server logic and bundled in production. Read more.

devServer

  • 默认值:{ watch: [] } lang=ts}

开发服务器选项。你可以使用 watch 让开发服务器在指定路径下的任何文件发生更改时重新加载。

¥Dev server options. You can use watch to make the dev server reload if any file changes in specified paths.

watchOptions

关注开发模式的选项。有关更多信息,请参阅 chokidar

¥Watch options for development mode. See chokidar for more information.

imports

自动导入选项。有关更多信息,请参阅 unjs/unimport

¥Auto import options. See unjs/unimport for more information.

plugins

  • 默认值:[]

Nitro 插件路径数组。它们将在首次初始化时按顺序执行。

¥An array of paths to nitro plugins. They will be executed by order on the first initialization.

请注意,Nitro 会自动在 plugins/ 目录和 了解更多 目录中注册插件。

¥Note that Nitro auto-register the plugins in the plugins/ directory, learn more.

virtual

  • 默认值:{}

动态虚拟导入名称与其内容的映射,或返回该映射的异步函数。

¥A map from dynamic virtual import names to their contents or an (async) function that returns it.

路由

¥Routing

baseURL

默认值:/ lang=ts} (或 NITRO_APP_BASE_URL 环境变量,如果提供)

¥Default: / (or NITRO_APP_BASE_URL environment variable if provided)

服务器主基准 URL。

¥Server's main base URL.

apiBaseURL

  • 默认值:/api

更改默认 API 基本 URL 前缀。

¥Changes the default api base URL prefix.

handlers

服务器处理程序和路由。

¥Server handlers and routes.

如果存在 server/routes/server/api/server/middleware/ 目录,它们将自动添加到处理程序数组中。

¥If server/routes/, server/api/ or server/middleware/ directories exist, they will be automatically added to the handlers array.

devHandlers

常规处理程序是指要由 rollup 导入和转换的处理程序的路径。

¥Regular handlers refer to the path of handlers to be imported and transformed by rollup.

在某些情况下,我们希望直接提供一个可编程使用的处理程序实例。

¥There are situations in that we directly want to provide a handler instance with programmatic usage.

我们可以使用 devHandlers,但请注意,它们仅在开发模式下可用,在生产构建中不可用。

¥We can use devHandlers but note that they are only available in development mode and not in production build.

对于示例:

¥For example:

import { defineEventHandler } from 'h3'

export default defineNitroConfig({
  devHandlers: [
    {
      route: '/',
      handler: defineEventHandler((event) => {
       console.log(event)
      })
    }
  ]
})
请注意,defineEventHandlerh3 库中的一个辅助函数。

devProxy

开发服务器的代理配置。

¥Proxy configuration for development server.

你可以使用此选项覆盖开发服务器路由和代理传递请求。

¥You can use this option to override development server routes and proxy-pass requests.

{
  devProxy: {
    '/proxy/test': 'http://localhost:3001',
    '/proxy/example': { target: 'https://example.com', changeOrigin: true }
  }
}

有关所有可用的目标选项,请参阅 unjs/httpxy

¥See unjs/httpxy for all available target options.

errorHandler

自定义运行时错误处理程序的路径。替换 nitro 的内置错误页面。错误处理程序被赋予 H3ErrorH3Event。如果处理程序返回一个 promise,则等待该 promise。处理程序应发送其自身的响应。以下是使用 h3 函数返回纯文本响应的示例。

¥Path to a custom runtime error handler. Replacing nitro's built-in error page. The error handler is given an H3Error and H3Event. If the handler returns a promise it is awaited. The handler is expected to send a response of its own. Below is an example where a plain-text response is returned using h3's functions.

示例:

¥Example:

export default defineNitroConfig({
  errorHandler: "~/error",
});

routeRules

🧪 实验性!

¥🧪 Experimental!

路由选项。它是从路由模式(遵循 unjs/radix3)到路由选项的映射。

¥Route options. It is a map from route pattern (following unjs/radix3) to route options.

设置 cache 选项后,匹配模式的处理程序将自动使用 defineCachedEventHandler 进行封装。

¥When cache option is set, handlers matching pattern will be automatically wrapped with defineCachedEventHandler.

请参阅 缓存 API 了解所有可用的缓存选项。

¥See the Cache API for all available cache options.

swr: true|numbercache: { swr: true, maxAge: number } 的快捷方式

示例:

¥Example:

routeRules: {
  '/blog/**': { swr: true },
  '/blog/**': { swr: 600 },
  '/blog/**': { static: true },
  '/blog/**': { cache: { /* cache options*/ } },
  '/assets/**': { headers: { 'cache-control': 's-maxage=0' } },
  '/api/v1/**': { cors: true, headers: { 'access-control-allow-methods': 'GET' } },
  '/old-page': { redirect: '/new-page' }, // uses status code 307 (Temporary Redirect)
  '/old-page2': { redirect: { to:'/new-page2', statusCode: 301 } },
  '/old-page/**': { redirect: '/new-page/**' },
  '/proxy/example': { proxy: 'https://example.com' },
  '/proxy/**': { proxy: '/api/**' },
}

prerender

默认值:

¥Default:

{
  autoSubfolderIndex: true,
  concurrency: 1,
  interval: 0,
  failOnError: false,
  crawlLinks: false,
  ignore: [],
  routes: [],
  retry: 3,
  retryDelay: 500
}

预渲染选项。任何指定的路由都将在构建期间获取,并作为静态资源复制到 .output/public 目录。

¥Prerendered options. Any route specified will be fetched during the build and copied to the .output/public directory as a static asset.

任何以 ignore 中列出的前缀开头或与正则表达式或函数匹配的路由(字符串)都将被忽略。

¥Any route (string) that starts with a prefix listed in ignore or matches a regular expression or function will be ignored.

如果 crawlLinks 设置为 true,则 Nitro 会默认从 / 开始(或从 routes 数组中的所有路由开始),并且对于 HTML 页面,Nitro 会提取 <a> 标签并对其进行预渲染。

¥If crawlLinks option is set to true, nitro starts with / by default (or all routes in routes array) and for HTML pages extracts <a> tags and prerender them as well.

你可以将 failOnError 选项设置为 true,以便在 Nitro 无法预渲染路由时出现错误时停止 CI。

¥You can set failOnError option to true to stop the CI when an error if Nitro could not prerender a route.

intervalconcurrency 选项允许你控制预渲染的速度,在调用外部 API 时,有助于避免达到某些速率限制。

¥The interval and concurrency options lets you control the speed of pre-rendering, can be useful to avoid hitting some rate-limit if you call external APIs.

设置 autoSubfolderIndex 允许你控制如何在 .output/public 目录中生成文件:

¥Set autoSubfolderIndex lets you control how to generate the files in the .output/public directory:

# autoSubfolderIndex: true (default)
/about -> .output/public/about/index.html
# autoSubfolderIndex: false
/about -> .output/public/about.html

当你的托管服务提供商没有提供有关尾部斜杠的选项时,此选项很有用。

¥This option is useful when your hosting provider does not give you an option regarding the trailing slash.

预渲染器将尝试渲染页面 3 次,每次延迟 500 毫秒。使用 retryretryDelay 更改此行为。

¥The prerenderer will attempt to render pages 3 times with a delay of 500ms. Use retry and retryDelay to change this behavior.

目录

¥Directories

rootDir

项目主目录

¥Project main directory

srcDir

-默认值:(与 rootDir 相同)

¥-Default : (same as rootDir)

项目源目录。除非另有说明,否则与 rootDir 相同。apiroutespluginsutilspublicmiddlewareassetstasks 文件夹的根目录。

¥Project source directory. Same as rootDir unless specified. Root directory for api, routes, plugins, utils, public, middleware, assets, and tasks folders.

scanDirs

  • 默认值:(数组为空时为源目录)

要扫描和自动注册文件的目录列表,例如 API 路由。

¥List of directories to scan and auto-register files, such as API routes.

apiDir

  • 默认值:api

定义用于扫描 API 路由处理程序的其他目录。

¥Defines a different directory to scan for api route handlers.

routesDir

  • 默认值:routes

定义用于扫描路由处理程序的其他目录。

¥Defines a different directory to scan for route handlers.

buildDir

  • 默认值:.nitro

nitro 用于生成构建相关文件的临时工作目录。

¥nitro's temporary working directory for generating build-related files.

output

  • 默认值:{ dir: '.output', serverDir: '.output/server', publicDir: '.output/public' }

生产包的输出目录。

¥Output directories for production bundle.

高级配置

¥Advanced

dev

  • 默认值:true 用于开发环境,false 用于生产环境。

⚠️ 注意!这是一个高级配置。如果配置错误,可能会出错。

¥⚠️ Caution! This is an advanced configuration. Things can go wrong if misconfigured.

typescript

默认值:{ generateTsConfig: true }

¥Default: { generateTsConfig: true }

nodeModulesDirs

⚠️ 注意!这是一个高级配置。如果配置错误,可能会出错。

¥⚠️ Caution! This is an advanced configuration. Things can go wrong if misconfigured.

解析模块时搜索的附加 node_modules。默认情况下,系统会添加用户目录。

¥Additional node_modules to search when resolving a module. By default user directory is added.

hooks

⚠️ 注意!这是一个高级配置。如果配置错误,可能会出错。

¥⚠️ Caution! This is an advanced configuration. Things can go wrong if misconfigured.

nitro hooks.有关更多信息,请参阅 unjs/hookable

¥nitro hooks. See unjs/hookable for more information.

commands

⚠️ 注意!这是一个高级配置。如果配置错误,可能会出错。

¥⚠️ Caution! This is an advanced configuration. Things can go wrong if misconfigured.

预览和部署命令提示通常由部署预设填充。

¥Preview and deploy command hints are usually filled by deployment presets.

devErrorHandler

⚠️ 注意!这是一个高级配置。如果配置错误,可能会出错。

¥⚠️ Caution! This is an advanced configuration. Things can go wrong if misconfigured.

用于处理开发错误的自定义错误处理函数。

¥A custom error handler function for development errors.

Rollup

rollupConfig

其他汇总配置。

¥Additional rollup configuration.

entry

Rollup 条目。

¥Rollup entry.

unenv

unjs/unenv 预设的选项。

¥Options for unjs/unenv preset.

alias

Rollup 别名选项。

¥Rollup aliases options.

minify

  • 默认值:false

压缩软件包。

¥Minify bundle.

inlineDynamicImports

避免创建块。

¥Avoid creating chunks.

sourceMap

启用源地图生成。参见 options

¥Enable source map generation. See options

  • 默认值:true

node

指定构建是否用于 Node.js。如果设置为 false,nitro 会尝试使用 unjs/unenv 模拟 Node.js 依赖并调整其行为。

¥Specify whether the build is used for Node.js or not. If set to false, nitro tries to mock Node.js dependencies using unjs/unenv and adjust its behavior.

analyze

如果启用,将在构建后使用 rollup-plugin-visualizer 分析服务器包。你还可以传递自定义选项。

¥If enabled, will analyze server bundle after build using rollup-plugin-visualizer. You can also pass your custom options.

moduleSideEffects

默认值:['unenv/polyfill/', 'node-fetch-native/polyfill']

¥Default: ['unenv/polyfill/', 'node-fetch-native/polyfill']

Rollup 特定选项。指定具有副作用的模块导入。

¥Rollup specific option. Specifies module imports that have side-effects

replace

Rollup 特定选项。

¥Rollup specific option.

commonJS

Rollup 特定选项。指定 rollup CommonJS 插件的附加配置。

¥Rollup specific option. Specifies additional configuration for the rollup CommonJS plugin.

预设选项

¥Preset options

firebase

firebase 函数预设的选项。参见 预设文档

¥The options for the firebase functions preset. See Preset Docs

vercel

vercel 预设的选项。参见 预设文档

¥The options for the vercel preset. See Preset Docs

cloudflare

cloudflare 预设的选项。参见 预设文档

¥The options for the cloudflare preset. See Preset Docs