Skip to content

配置参考

以下参考涵盖了 Astro 中所有支持的配置选项。要了解有关配置 Astro 的更多信息,请阅读我们的 配置 Astro 指南。

¥The following reference covers all supported configuration options in Astro. To learn more about configuring Astro, read our guide on Configuring Astro.

astro.config.mjs
import { defineConfig } from 'astro/config'
export default defineConfig({
// your configuration options here...
})

¥Top-Level Options

类型:string

¥Type: string

你的最终部署 URL。Astro 使用此完整 URL 在最终版本中生成站点地图和规范 URL。强烈建议你设置此配置以充分利用 Astro。

¥Your final, deployed URL. Astro uses this full URL to generate your sitemap and canonical URLs in your final build. It is strongly recommended that you set this configuration to get the most out of Astro.

{
site: 'https://www.my-site.dev'
}

类型:string

¥Type: string

要部署到的基本路径。Astro 将使用此路径作为开发和生产构建中的页面和资源的根。

¥The base path to deploy to. Astro will use this path as the root for your pages and assets both in development and in production build.

在下面的示例中,astro dev 将在 /docs 启动你的服务器。

¥In the example below, astro dev will start your server at /docs.

{
base: '/docs'
}

使用此选项时,所有静态资源导入和 URL 都应添加基础作为前缀。你可以通过 import.meta.env.BASE_URL 访问该值。

¥When using this option, all of your static asset imports and URLs should add the base as a prefix. You can access this value via import.meta.env.BASE_URL.

import.meta.env.BASE_URL 的值将由你的 trailingSlash 配置决定,无论你为 base 设置什么值。

¥The value of import.meta.env.BASE_URL will be determined by your trailingSlash config, no matter what value you have set for base.

如果设置了 trailingSlash: "always",则始终包含尾部斜杠。如果设置了 trailingSlash: "never",则 BASE_URL 将不包含尾部斜线,即使 base 包含斜线也是如此。

¥A trailing slash is always included if trailingSlash: "always" is set. If trailingSlash: "never" is set, BASE_URL will not include a trailing slash, even if base includes one.

此外,Astro 将在内部操作 config.base 的配置值,然后再将其用于集成。集成读取的 config.base 值也将由你的 trailingSlash 配置以相同的方式确定。

¥Additionally, Astro will internally manipulate the configured value of config.base before making it available to integrations. The value of config.base as read by integrations will also be determined by your trailingSlash configuration in the same way.

在下面的例子中,import.meta.env.BASE_URLconfig.base 处理后的值都是 /docs

¥In the example below, the values of import.meta.env.BASE_URL and config.base when processed will both be /docs:

{
base: '/docs/',
trailingSlash: "never"
}

在下面的例子中,import.meta.env.BASE_URLconfig.base 处理后的值都是 /docs/

¥In the example below, the values of import.meta.env.BASE_URL and config.base when processed will both be /docs/:

{
base: '/docs',
trailingSlash: "always"
}

类型:'always' | 'never' | 'ignore'
默认:'ignore'

¥Type: 'always' | 'never' | 'ignore'
Default: 'ignore'

设置开发服务器的路由匹配行为。从以下选项中进行选择:

¥Set the route matching behavior of the dev server. Choose from the following options:

  • 'always' - 仅匹配包含尾部斜杠的 URL(例如:“/foo/“)

  • 'never' - 切勿匹配包含尾部斜杠的 URL(例如:“/foo”)

  • 'ignore' - 匹配 URL,无论尾随 ”/” 是否存在

如果你的生产主机对尾部斜杠如何工作或不工作有严格的处理,请使用此配置选项。

¥Use this configuration option if your production host has strict handling of how trailing slashes work or do not work.

如果你希望自己更严格,也可以设置此项,这样带或不带尾部斜杠的 URL 在开发过程中都不起作用。

¥You can also set this if you prefer to be more strict yourself, so that URLs with or without trailing slashes won’t work during development.

{
// Example: Require a trailing slash during development
trailingSlash: 'always'
}

也可以看看:

¥See Also:

  • build.format

类型:Record.<string, RedirectConfig>
默认:{}

¥Type: Record.<string, RedirectConfig>
Default: {}

Added in: astro@2.9.0

指定重定向映射,其中键是要匹配的路由,值是要重定向到的路径。

¥Specify a mapping of redirects where the key is the route to match and the value is the path to redirect to.

你可以重定向静态和动态路由,但只能重定向到同一类型的路由。例如,你不能进行 '/article': '/blog/[...slug]' 重定向。

¥You can redirect both static and dynamic routes, but only to the same kind of route. For example you cannot have a '/article': '/blog/[...slug]' redirect.

{
redirects: {
'/old': '/new',
'/blog/[...slug]': '/articles/[...slug]',
}
}

对于未安装适配器的静态生成的站点,这将使用 <meta http-equiv="refresh"> 标签 生成客户端重定向,并且不支持状态代码。

¥For statically-generated sites with no adapter installed, this will produce a client redirect using a <meta http-equiv="refresh"> tag and does not support status codes.

output: static 模式下使用 SSR 或静态适配器时,支持状态代码。Astro 将提供状态为 301 的重定向 GET 请求,并为任何其他请求方法使用状态 308

¥When using SSR or with a static adapter in output: static mode, status codes are supported. Astro will serve redirected GET requests with a status of 301 and use a status of 308 for any other request method.

你可以使用重定向配置中的对象自定义 重定向状态码

¥You can customize the redirection status code using an object in the redirect config:

{
redirects: {
'/other': {
status: 302,
destination: '/place',
},
}
}

类型:'static' | 'server'
默认:'static'

¥Type: 'static' | 'server'
Default: 'static'

指定构建的输出目标。

¥Specifies the output target for builds.

  • 'static' - 默认情况下预渲染所有页面,如果你的所有页面均未选择退出预渲染,则输出完全静态的站点。

  • 'server' - 默认情况下,对所有页面使用服务器端渲染 (SSR),始终输出服务器渲染的站点。

import { defineConfig } from 'astro/config';
export default defineConfig({
output: 'static'
})

也可以看看:

¥See Also:

  • adapter

类型:AstroIntegration

¥Type: AstroIntegration

使用构建适配器部署到你最喜欢的服务器、无服务器或边缘主机。导入我们针对 NetlifyVercel 等的第一方适配器之一以使用 Astro SSR。

¥Deploy to your favorite server, serverless, or edge host with build adapters. Import one of our first-party adapters for Netlify, Vercel, and more to engage Astro SSR.

查看我们的按需渲染指南 了解有关 SSR 的更多信息,我们的部署指南 了解完整的主机列表。

¥See our On-demand Rendering guide for more on SSR, and our deployment guides for a complete list of hosts.

import netlify from '@astrojs/netlify';
{
// Example: Build for Netlify serverless deployment
adapter: netlify(),
}

也可以看看:

¥See Also:

  • output

类型:AstroIntegration[]

¥Type: AstroIntegration[]

通过自定义集成扩展 Astro。集成是你添加框架支持(如 Solid.js)、新功能(如站点地图)和新库(如 Partytown)的一站式存储。

¥Extend Astro with custom integrations. Integrations are your one-stop-shop for adding framework support (like Solid.js), new features (like sitemaps), and new libraries (like Partytown).

请阅读我们的 集成指南 以获取 Astro Integrations 入门帮助。

¥Read our Integrations Guide for help getting started with Astro Integrations.

import react from '@astrojs/react';
import tailwind from '@astrojs/tailwind';
{
// Example: Add React + Tailwind support to Astro
integrations: [react(), tailwind()]
}

类型:string
CLI:--root
默认:"."(当前工作目录)

¥Type: string
CLI: --root
Default: "." (current working directory)

仅当你在项目根目录以外的目录中运行 astro CLI 命令时,才应提供此选项。通常,此选项通过 CLI 而不是 Astro 配置文件提供,因为 Astro 需要知道你的项目根目录才能找到你的配置文件。

¥You should only provide this option if you run the astro CLI commands in a directory other than the project root directory. Usually, this option is provided via the CLI instead of the Astro config file, since Astro needs to know your project root before it can locate your config file.

如果你提供相对路径(例如:--root: './my-project'),Astro 将根据你当前的工作目录解析它。

¥If you provide a relative path (ex: --root: './my-project') Astro will resolve it against your current working directory.

¥Examples

{
root: './my-project-directory'
}
终端窗口
$ astro build --root ./my-project-directory

类型:string
默认:"./src"

¥Type: string
Default: "./src"

设置 Astro 将从中读取你的网站的目录。

¥Set the directory that Astro will read your site from.

该值可以是绝对文件系统路径或相对于项目根目录的路径。

¥The value can be either an absolute file system path or a path relative to the project root.

{
srcDir: './www'
}

类型:string
默认:"./public"

¥Type: string
Default: "./public"

设置静态资源的目录。此目录中的文件在开发期间在 / 提供,并在构建期间复制到构建目录。这些文件始终按原样提供或复制,无需转换或打包。

¥Set the directory for your static assets. Files in this directory are served at / during dev and copied to your build directory during build. These files are always served or copied as-is, without transform or bundling.

该值可以是绝对文件系统路径或相对于项目根目录的路径。

¥The value can be either an absolute file system path or a path relative to the project root.

{
publicDir: './my-custom-publicDir-directory'
}

类型:string
默认:"./dist"

¥Type: string
Default: "./dist"

设置 astro build 将最终构建写入的目录。

¥Set the directory that astro build writes your final build to.

该值可以是绝对文件系统路径或相对于项目根目录的路径。

¥The value can be either an absolute file system path or a path relative to the project root.

{
outDir: './my-custom-build-directory'
}

也可以看看:

¥See Also:

  • build.server

类型:string
默认:"./node_modules/.astro"

¥Type: string
Default: "./node_modules/.astro"

设置缓存构建工件的目录。该目录中的文件将在后续构建中使用,以加快构建时间。

¥Set the directory for caching build artifacts. Files in this directory will be used in subsequent builds to speed up the build time.

该值可以是绝对文件系统路径或相对于项目根目录的路径。

¥The value can be either an absolute file system path or a path relative to the project root.

{
cacheDir: './my-custom-cache-directory'
}

类型:boolean
默认:true

¥Type: boolean
Default: true

该选项可缩小 HTML 输出并减小 HTML 文件的大小。

¥This is an option to minify your HTML output and reduce the size of your HTML files.

默认情况下,Astro 会以无损方式从 .astro 组件中删除 HTML 中的空格(包括换行符)。可以根据需要保留一些空白以保留 HTML 的视觉渲染。这在开发模式和最终构建中都会发生。

¥By default, Astro removes whitespace from your HTML, including line breaks, from .astro components in a lossless manner. Some whitespace may be kept as needed to preserve the visual rendering of your HTML. This occurs both in development mode and in the final build.

要禁用 HTML 压缩,请将 compressHTML 设置为 false。

¥To disable HTML compression, set compressHTML to false.

{
compressHTML: false
}

类型:'where' | 'class' | 'attribute'
默认:'attribute'

¥Type: 'where' | 'class' | 'attribute'
Default: 'attribute'

Added in: astro@2.4

指定 Astro 组件内用于确定样式范围的策略。从中选择:

¥Specify the strategy used for scoping styles within Astro components. Choose from:

  • 'where' - 使用 :where 选择器,不会导致特异性增加。

  • 'class' - 使用基于类的选择器,导致特异性增加+1。

  • 'attribute' - 使用 data- 属性,造成+1 专一性提升。

当你想要确保 Astro 组件中的元素选择器覆盖全局样式默认值(例如来自全局样式表)时,使用 'class' 会很有帮助。使用 'where' 可以让你更好地控制特异性,但要求你使用更高特异性的选择器、图层和其他工具来控制应用哪些选择器。当你操作元素的 class 属性并且需要避免你自己的样式逻辑与 Astro 的样式应用之间发生冲突时,使用 'attribute' 非常有用。

¥Using 'class' is helpful when you want to ensure that element selectors within an Astro component override global style defaults (e.g. from a global stylesheet). Using 'where' gives you more control over specificity, but requires that you use higher-specificity selectors, layers, and other tools to control which selectors are applied. Using 'attribute' is useful when you are manipulating the class attribute of elements and need to avoid conflicts between your own styling logic and Astro’s application of styles.

类型:Record.<"checkOrigin", boolean> | undefined
默认:{checkOrigin: true}

¥Type: Record.<"checkOrigin", boolean> | undefined
Default: {checkOrigin: true}

Added in: astro@4.9.0

为 Astro 网站启用安全措施。

¥Enables security measures for an Astro website.

这些功能仅适用于使用 server 模式按需渲染 (SSR) 的页面或在 static 模式下选择退出预渲染的页面。

¥These features only exist for pages rendered on demand (SSR) using server mode or pages that opt out of prerendering in static mode.

默认情况下,Astro 会自动检查“origin”标头是否与按需渲染页面中每个请求发送的 URL 匹配。你可以通过将 checkOrigin 设置为 false 来禁用此行为:

¥By default, Astro will automatically check that the “origin” header matches the URL sent by each request in on-demand rendered pages. You can disable this behavior by setting checkOrigin to false:

astro.config.mjs
export default defineConfig({
output: "server",
security: {
checkOrigin: false
}
})

类型:boolean
默认:true

¥Type: boolean
Default: true

Added in: astro@4.9.0

检查所有现代浏览器自动传递的 “origin” 标头是否与每个 Request 发送的 URL 匹配。这用于提供跨站点请求伪造 (CSRF) 保护。

¥Performs a check that the “origin” header, automatically passed by all modern browsers, matches the URL sent by each Request. This is used to provide Cross-Site Request Forgery (CSRF) protection.

”origin” 检查仅针对按需渲染的页面执行,并且仅针对具有以下 content-type 标头之一的请求 POSTPATCHDELETEPUT 执行:'application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'.

¥The “origin” check is executed only for pages rendered on demand, and only for the requests POST, PATCH, DELETE and PUT with one of the following content-type headers: 'application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'.

如果 “origin” 标头与请求的 pathname 不匹配,Astro 将返回 403 状态代码并且不会渲染页面。

¥If the “origin” header doesn’t match the pathname of the request, Astro will return a 403 status code and will not render the page.

类型:ViteUserConfig

¥Type: ViteUserConfig

将附加配置选项传递给 Vite。当 Astro 不支持你可能需要的某些高级配置时很有用。

¥Pass additional configuration options to Vite. Useful when Astro doesn’t support some advanced configuration that you may need.

查看有关 vite.dev 的完整 vite 配置对象文档。

¥View the full vite configuration object documentation on vite.dev.

¥Examples

{
vite: {
ssr: {
// Example: Force a broken package to skip SSR processing, if needed
external: ['broken-npm-package'],
}
}
}
{
vite: {
// Example: Add custom vite plugins directly to your Astro project
plugins: [myPlugin()],
}
}

¥Build Options

类型:('file' | 'directory' | 'preserve')
默认:'directory'

¥Type: ('file' | 'directory' | 'preserve')
Default: 'directory'

控制每个页面的输出文件格式。此值可以由适配器为你设置。

¥Control the output file format of each page. This value may be set by an adapter for you.

  • 'file':Astro 将为每个页面路由生成一个 HTML 文件。(例如 src/pages/about.astrosrc/pages/about/index.astro 都构建文件 /about.html

  • 'directory':Astro 将为每个页面生成一个带有嵌套 index.html 文件的目录。(例如 src/pages/about.astrosrc/pages/about/index.astro 都构建文件 /about/index.html

  • 'preserve':Astro 将生成与源文件夹中显示的完全相同的 HTML 文件。(例如 src/pages/about.astro 构建 /about.htmlsrc/pages/about/index.astro 构建文件 /about/index.html

{
build: {
// Example: Generate `page.html` instead of `page/index.html` during build.
format: 'file'
}
}

¥Effect on Astro.url

设置 build.format 控制构建过程中 Astro.url 的设置。几时:

¥Setting build.format controls what Astro.url is set to during the build. When it is:

  • directory - Astro.url.pathname 将包含一个尾部斜杠以模仿文件夹行为。(例如 /foo/

  • file - Astro.url.pathname 将包含 .html。(例如 /foo.html

这意味着当你使用 new URL('./relative', Astro.url) 创建相对 URL 时,你将在开发和构建之间获得一致的行为。

¥This means that when you create relative URLs using new URL('./relative', Astro.url), you will get consistent behavior between dev and build.

为了防止 dev 中的尾部斜杠行为不一致,你可以根据你的构建格式将 trailingSlash 选项 限制为 'always''never'

¥To prevent inconsistencies with trailing slash behaviour in dev, you can restrict the trailingSlash option to 'always' or 'never' depending on your build format:

  • directory - 设置 trailingSlash: 'always'

  • file - 设置 trailingSlash: 'never'

类型:string
默认:'./client'

¥Type: string
Default: './client'

在构建具有服务器渲染页面的网站时,控制客户端 CSS 和 JavaScript 的输出目录。outDir 控制代码的构建位置。

¥Controls the output directory of your client-side CSS and JavaScript when building a website with server-rendered pages. outDir controls where the code is built to.

该值是相对于 outDir 的。

¥This value is relative to the outDir.

{
output: 'server',
build: {
client: './client'
}
}

类型:string
默认:'./server'

¥Type: string
Default: './server'

构建 SSR 时控制服务器 JavaScript 的输出目录。

¥Controls the output directory of server JavaScript when building to SSR.

该值是相对于 outDir 的。

¥This value is relative to the outDir.

{
build: {
server: './server'
}
}

类型:string
默认:'_astro'

¥Type: string
Default: '_astro'

Added in: astro@2.0.0

指定构建输出中 Astro 生成的资源(例如打包的 JS 和 CSS)应所在的目录。

¥Specifies the directory in the build output where Astro-generated assets (bundled JS and CSS for example) should live.

{
build: {
assets: '_custom'
}
}

也可以看看:

¥See Also:

  • outDir

类型:string | Record.<string, string>
默认:undefined

¥Type: string | Record.<string, string>
Default: undefined

Added in: astro@2.2.0

指定 Astro 生成的资源链接的前缀。如果资源是从与当前站点不同的域提供的,则可以使用此功能。

¥Specifies the prefix for Astro-generated asset links. This can be used if assets are served from a different domain than the current site.

这需要将本地 ./dist/_astro 文件夹中的资源上传到远程域上相应的 /_astro/ 文件夹。要重命名 _astro 路径,请在 build.assets 中指定新目录。

¥This requires uploading the assets in your local ./dist/_astro folder to a corresponding /_astro/ folder on the remote domain. To rename the _astro path, specify a new directory in build.assets.

要获取上传到同一域(例如 https://cdn.example.com/_astro/...)的所有资源,请将 assetsPrefix 设置为根域作为字符串(无论你的 base 配置如何):

¥To fetch all assets uploaded to the same domain (e.g. https://cdn.example.com/_astro/...), set assetsPrefix to the root domain as a string (regardless of your base configuration):

{
build: {
assetsPrefix: 'https://cdn.example.com'
}
}

添加于:astro@4.5.0

¥Added in: astro@4.5.0

你还可以将对象传递给 assetsPrefix 以指定每种文件类型的不同域。在这种情况下,fallback 属性是必需的,并且将默认用于任何其他文件。

¥You can also pass an object to assetsPrefix to specify a different domain for each file type. In this case, a fallback property is required and will be used by default for any other files.

{
build: {
assetsPrefix: {
'js': 'https://js.cdn.example.com',
'mjs': 'https://js.cdn.example.com',
'css': 'https://css.cdn.example.com',
'fallback': 'https://cdn.example.com'
}
}
}

类型:string
默认:'entry.mjs'

¥Type: string
Default: 'entry.mjs'

指定构建 SSR 时服务器入口点的文件名。此入口点通常取决于你要部署到的主机,并将由你的适配器为你设置。

¥Specifies the file name of the server entrypoint when building to SSR. This entrypoint is usually dependent on which host you are deploying to and will be set by your adapter for you.

请注意,建议该文件以 .mjs 结尾,以便运行时检测到该文件是 JavaScript 模块。

¥Note that it is recommended that this file ends with .mjs so that the runtime detects that the file is a JavaScript module.

{
build: {
serverEntry: 'main.mjs'
}
}

类型:boolean
默认:true

¥Type: boolean
Default: true

Added in: astro@2.6.0

指定在构建期间是否将重定向输出为 HTML。该选项仅适用于 output: 'static' 模式;在 SSR 中,重定向的处理方式与所有响应相同。

¥Specifies whether redirects will be output to HTML during the build. This option only applies to output: 'static' mode; in SSR redirects are treated the same as all responses.

此选项主要供具有用于重定向的特殊配置文件并且不需要/不想要基于 HTML 的重定向的适配器使用。

¥This option is mostly meant to be used by adapters that have special configuration files for redirects and do not need/want HTML based redirects.

{
build: {
redirects: false
}
}

类型:'always' | 'auto' | 'never'
默认:auto

¥Type: 'always' | 'auto' | 'never'
Default: auto

Added in: astro@2.6.0

控制项目样式是在单独的 css 文件中发送到浏览器还是内联到 <style> 标记中。从以下选项中进行选择:

¥Control whether project styles are sent to the browser in a separate css file or inlined into <style> tags. Choose from the following options:

  • 'always' - 项目样式内联到 <style> 标签中

  • 'auto' - 仅内联小于 ViteConfig.build.assetsInlineLimit(默认值:4kb)的样式表。否则,项目样式将在外部样式表中发送。

  • 'never' - 项目样式在外部样式表中发送

{
build: {
inlineStylesheets: `never`,
},
}

类型:number
默认:1

¥Type: number
Default: 1

Added in: astro@4.16.0

要并行构建的页面数。

¥The number of pages to build in parallel.

在大多数情况下,你不应更改 1 的默认值。

¥In most cases, you should not change the default value of 1.

仅当其他尝试减少总体渲染时间(例如批处理或缓存长时间运行的任务,如获取调用或数据访问)无法实现或不足时,才使用此选项。如果数字设置得太高,由于内存资源不足以及 JS 是单线程的,页面渲染可能会变慢。

¥Use this option only when other attempts to reduce the overall rendering time (e.g. batch or cache long running tasks like fetch calls or data access) are not possible or are insufficient. If the number is set too high, page rendering may slow down due to insufficient memory resources and because JS is single-threaded.

{
build: {
concurrency: 2
}
}

¥Server Options

自定义 Astro 开发服务器,供 astro devastro preview 使用。

¥Customize the Astro dev server, used by both astro dev and astro preview.

{
server: { port: 1234, host: true}
}

要根据命令运行(“dev”,“preview”)设置不同的配置,也可以将函数传递给此配置选项。

¥To set different configuration based on the command run (“dev”, “preview”) a function can also be passed to this configuration option.

{
// Example: Use the function syntax to customize based on command
server: ({ command }) => ({ port: command === 'dev' ? 4321 : 4000 })
}

类型:string | boolean
默认:false

¥Type: string | boolean
Default: false

Added in: astro@0.24.0

设置服务器应监听的网络 IP 地址(即非本地主机 IP)。

¥Set which network IP addresses the server should listen on (i.e. non-localhost IPs).

  • false - 不要在网络上公开 IP 地址

  • true - 监听所有地址,包括 LAN 和公共地址

  • [custom-address] - 在 [custom-address] 处的网络 IP 地址上公开(例如:192.168.0.1

类型:number
默认:4321

¥Type: number
Default: 4321

设置服务器应监听哪个端口。

¥Set which port the server should listen on.

如果给定的端口已被使用,Astro 将自动尝试下一个可用端口。

¥If the given port is already in use, Astro will automatically try the next available port.

{
server: { port: 8080 }
}

类型:string | boolean
默认:false

¥Type: string | boolean
Default: false

Added in: astro@4.1.0

控制开发服务器是否应在启动时在浏览器窗口中打开。

¥Controls whether the dev server should open in your browser window on startup.

传递完整的 URL 字符串(例如“http://example.com”)或路径名(例如 “/about”)以指定要打开的 URL。

¥Pass a full URL string (e.g. “http://example.com”) or a pathname (e.g. “/about”) to specify the URL to open.

{
server: { open: "/about" }
}

类型:OutgoingHttpHeaders
默认:{}

¥Type: OutgoingHttpHeaders
Default: {}

Added in: astro@1.7.0

设置要在 astro devastro preview 中发送的自定义 HTTP 响应标头。

¥Set custom HTTP response headers to be sent in astro dev and astro preview.

¥Dev Toolbar Options

类型:boolean
默认:true

¥Type: boolean
Default: true

是否启用 Astro Dev 工具栏。此工具栏允许你检查页面岛,查看有关性能和可访问性的有用审核等等。

¥Whether to enable the Astro Dev Toolbar. This toolbar allows you to inspect your page islands, see helpful audits on performance and accessibility, and more.

此选项的作用范围为整个项目,若要仅为自己禁用工具栏,请运行 npm run astro preferences disable devToolbar。要禁用所有 Astro 项目的工具栏,请运行 npm run astro preferences disable devToolbar --global

¥This option is scoped to the entire project, to only disable the toolbar for yourself, run npm run astro preferences disable devToolbar. To disable the toolbar for all your Astro projects, run npm run astro preferences disable devToolbar --global.

¥Prefetch Options

类型:boolean | object

¥Type: boolean | object

启用网站上链接的预取以提供更快的页面转换。(默认情况下在使用 <ClientRouter /> 路由的页面上启用。设置 prefetch: false 以选择退出此行为。)

¥Enable prefetching for links on your site to provide faster page transitions. (Enabled by default on pages using the <ClientRouter /> router. Set prefetch: false to opt out of this behaviour.)

此配置会自动将预取脚本添加到项目中的每个页面,以便你访问 data-astro-prefetch 属性。将此属性添加到页面上的任何 <a /> 链接以启用该页面的预取。

¥This configuration automatically adds a prefetch script to every page in the project giving you access to the data-astro-prefetch attribute. Add this attribute to any <a /> link on your page to enable prefetching for that page.

<a href="/about" data-astro-prefetch>About</a>

使用 prefetch.defaultStrategyprefetch.prefetchAll 选项进一步自定义默认预取行为。

¥Further customize the default prefetching behavior using the prefetch.defaultStrategy and prefetch.prefetchAll options.

请参阅 预取指南 了解更多信息。

¥See the Prefetch guide for more information.

类型:boolean

¥Type: boolean

为所有链接启用预取,包括那些没有 data-astro-prefetch 属性的链接。当使用 <ClientRouter /> 路由时,该值默认为 true。否则,默认值为 false

¥Enable prefetching for all links, including those without the data-astro-prefetch attribute. This value defaults to true when using the <ClientRouter /> router. Otherwise, the default value is false.

prefetch: {
prefetchAll: true
}

设置为 true 时,你可以通过在任何单独的链接上设置 data-astro-prefetch="false" 来单独禁用预取。

¥When set to true, you can disable prefetching individually by setting data-astro-prefetch="false" on any individual links.

<a href="/about" data-astro-prefetch="false">About</a>

类型:'tap' | 'hover' | 'viewport' | 'load'
默认:'hover'

¥Type: 'tap' | 'hover' | 'viewport' | 'load'
Default: 'hover'

在没有值的链接上设置 data-astro-prefetch 属性时使用的默认预取策略。

¥The default prefetch strategy to use when the data-astro-prefetch attribute is set on a link with no value.

  • 'tap':在单击链接之前预取。

  • 'hover':当你将鼠标悬停在链接上或将焦点放在链接上时预取。(默认)

  • 'viewport':当链接进入视口时预取。

  • 'load':页面加载后预取页面上的所有链接。

你可以覆盖此默认值,并通过在属性上设置值来为任何单个链接选择不同的策略。

¥You can override this default value and select a different strategy for any individual link by setting a value on the attribute.

<a href="/about" data-astro-prefetch="viewport">About</a>

¥Image Options

类型:Object
默认:{route: '/_image', entrypoint: undefined}

¥Type: Object
Default: {route: '/_image', entrypoint: undefined}

Added in: astro@3.1.0

设置用于 dev 和 SSR 中图片优化的端点。可以将 entrypoint 属性设置为 undefined 以使用默认图片端点。

¥Set the endpoint to use for image optimization in dev and SSR. The entrypoint property can be set to undefined to use the default image endpoint.

{
image: {
// Example: Use a custom image endpoint at `/custom_endpoint`
endpoint: {
route: '/custom_endpoint',
entrypoint: 'src/my_endpoint.ts',
},
},
}

类型:Object
默认:{entrypoint: 'astro/assets/services/sharp', config?: {}}

¥Type: Object
Default: {entrypoint: 'astro/assets/services/sharp', config?: {}}

Added in: astro@2.1.0

设置使用哪个图片服务来支持 Astro 的资源。

¥Set which image service is used for Astro’s assets support.

该值应该是一个对象,带有供图片服务使用的入口点,并且可以选择传递给服务的配置对象。

¥The value should be an object with an entrypoint for the image service to use and optionally, a config object to pass to the service.

服务入口点可以是包含的服务之一,也可以是第三方包。

¥The service entrypoint can be either one of the included services, or a third-party package.

{
image: {
// Example: Enable the Sharp-based image service with a custom config
service: {
entrypoint: 'astro/assets/services/sharp',
config: {
limitInputPixels: false,
},
},
},
}

image.service.config.limitInputPixels

标题部分 image.service.config.limitInputPixels

类型:number | boolean
默认:true

¥Type: number | boolean
Default: true

Added in: astro@4.1.0

是否限制 Sharp 图片服务将处理的图片大小。

¥Whether or not to limit the size of images that the Sharp image service will process.

设置 false 以绕过 Sharp 图片服务的默认图片大小限制并处理大图片。

¥Set false to bypass the default image size limit for the Sharp image service and process large images.

类型:Array.<string>
默认:{domains: []}

¥Type: Array.<string>
Default: {domains: []}

Added in: astro@2.10.10

定义用于远程图片优化的允许图片源域的列表。Astro 不会优化其他远程图片。

¥Defines a list of permitted image source domains for remote image optimization. No other remote images will be optimized by Astro.

此选项需要一组单独的域名作为字符串。不允许使用通配符。相反,使用 image.remotePatterns 定义允许的源 URL 模式的列表。

¥This option requires an array of individual domain names as strings. Wildcards are not permitted. Instead, use image.remotePatterns to define a list of allowed source URL patterns.

astro.config.mjs
{
image: {
// Example: Allow remote image optimization from a single domain
domains: ['astro.build'],
},
}

类型:Array.<RemotePattern>
默认:{remotePatterns: []}

¥Type: Array.<RemotePattern>
Default: {remotePatterns: []}

Added in: astro@2.10.10

定义用于远程图片优化的允许图片源 URL 模式的列表。

¥Defines a list of permitted image source URL patterns for remote image optimization.

remotePatterns 可以配置四个属性:

¥remotePatterns can be configured with four properties:

  1. protocol
  2. hostname
  3. port
  4. pathname
{
image: {
// Example: allow processing all images from your aws s3 bucket
remotePatterns: [{
protocol: 'https',
hostname: '**.amazonaws.com',
}],
},
}

你可以使用通配符来定义允许的 hostnamepathname 值,如下所述。否则,只会配置提供的确切值:hostname

¥You can use wildcards to define the permitted hostname and pathname values as described below. Otherwise, only the exact values provided will be configured: hostname:

  • 以 ’**.’ 开头以允许所有子域(‘endsWith’)。

  • 以 ’*.’ 开头以仅允许一级子域。

pathname

  • 以 ’/**’ 结尾以允许所有子路由(‘startsWith’)。

  • 以 ’/*’ 结尾仅允许一级子路由。

类型:ImageLayout
默认:undefined

¥Type: ImageLayout
Default: undefined

响应式图片的默认布局类型。可以通过图片组件上的 layout prop 覆盖。需要启用 experimental.responsiveImages 标志。

¥The default layout type for responsive images. Can be overridden by the layout prop on the image component. Requires the experimental.responsiveImages flag to be enabled.

  • responsive - 图片将缩放以适合容器,保持其纵横比,但不会超过指定的尺寸。

  • fixed - 图片将保持其原始尺寸。

  • full-width - 图片将缩放以适合容器,并保持其纵横比。

image.experimentalObjectFit

标题部分 image.experimentalObjectFit

类型:ImageFit
默认:"cover"

¥Type: ImageFit
Default: "cover"

响应式图片的默认 object-fit 值。可以通过图片组件上的 fit prop 覆盖。需要启用 experimental.responsiveImages 标志。

¥The default object-fit value for responsive images. Can be overridden by the fit prop on the image component. Requires the experimental.responsiveImages flag to be enabled.

image.experimentalObjectPosition

标题部分 image.experimentalObjectPosition

类型:string
默认:"center"

¥Type: string
Default: "center"

响应式图片的默认 object-position 值。可以通过图片组件上的 position prop 覆盖。需要启用 experimental.responsiveImages 标志。

¥The default object-position value for responsive images. Can be overridden by the position prop on the image component. Requires the experimental.responsiveImages flag to be enabled.

image.experimentalBreakpoints

标题部分 image.experimentalBreakpoints

类型:Array.<number>
默认:[640, 750, 828, 1080, 1280, 1668, 2048, 2560] | [640, 750, 828, 960, 1080, 1280, 1668, 1920, 2048, 2560, 3200, 3840, 4480, 5120, 6016]

¥Type: Array.<number>
Default: [640, 750, 828, 1080, 1280, 1668, 2048, 2560] | [640, 750, 828, 960, 1080, 1280, 1668, 1920, 2048, 2560, 3200, 3840, 4480, 5120, 6016]

用于生成响应式图片的断点。需要启用 experimental.responsiveImages 标志。完整列表通常不使用,但会根据源和输出大小进行过滤。使用的默认值取决于使用的是本地还是远程图片服务。对于远程服务,使用更全面的列表,因为只生成所需的大小。对于本地服务,列表较短,以减少生成的图片数量。

¥The breakpoints used to generate responsive images. Requires the experimental.responsiveImages flag to be enabled. The full list is not normally used, but is filtered according to the source and output size. The defaults used depend on whether a local or remote image service is used. For remote services the more comprehensive list is used, because only the required sizes are generated. For local services, the list is shorter to reduce the number of images generated.

¥Markdown Options

类型:Partial<ShikiConfig>

¥Type: Partial<ShikiConfig>

Shiki 是我们默认的语法高亮器。你可以通过 markdown.shikiConfig 对象配置所有选项:

¥Shiki is our default syntax highlighter. You can configure all options via the markdown.shikiConfig object:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
markdown: {
shikiConfig: {
// Choose from Shiki's built-in themes (or add your own)
// https://shiki.style/themes
theme: 'dracula',
// Alternatively, provide multiple themes
// See note below for using dual light/dark themes
themes: {
light: 'github-light',
dark: 'github-dark',
},
// Disable the default colors
// https://shiki.style/guide/dual-themes#without-default-color
// (Added in v4.12.0)
defaultColor: false,
// Add custom languages
// Note: Shiki has countless langs built-in, including .astro!
// https://shiki.style/languages
langs: [],
// Add custom aliases for languages
// Map an alias to a Shiki language ID: https://shiki.style/languages#bundled-languages
// https://shiki.style/guide/load-lang#custom-language-aliases
langAlias: {
cjs: "javascript"
},
// Enable word wrap to prevent horizontal scrolling
wrap: true,
// Add custom transformers: https://shiki.style/guide/transformers
// Find common transformers: https://shiki.style/packages/transformers
transformers: [],
},
},
});

有关用法和示例,请参阅 代码语法高亮指南

¥See the code syntax highlighting guide for usage and examples.

类型:'shiki' | 'prism' | false
默认:shiki

¥Type: 'shiki' | 'prism' | false
Default: shiki

如果有的话,对 Markdown 代码块(“```”)使用哪种语法高亮器。这决定了 Astro 将应用于你的 Markdown 代码块的 CSS 类。

¥Which syntax highlighter to use for Markdown code blocks (```), if any. This determines the CSS classes that Astro will apply to your Markdown code blocks.

{
markdown: {
// Example: Switch to use prism for syntax highlighting in Markdown
syntaxHighlight: 'prism',
}
}

类型:RemarkPlugins

¥Type: RemarkPlugins

通过 remark 插件 来自定义 Markdown 的构建方式。你可以导入并应用插件函数(推荐),或将插件名称作为字符串传递。

¥Pass remark plugins to customize how your Markdown is built. You can import and apply the plugin function (recommended), or pass the plugin name as a string.

import remarkToc from 'remark-toc';
{
markdown: {
remarkPlugins: [ [remarkToc, { heading: "contents"} ] ]
}
}

类型:RehypePlugins

¥Type: RehypePlugins

传递 rehype 插件 来自定义 Markdown 输出 HTML 的处理方式。你可以导入并应用插件函数(推荐),或将插件名称作为字符串传递。

¥Pass rehype plugins to customize how your Markdown’s output HTML is processed. You can import and apply the plugin function (recommended), or pass the plugin name as a string.

import { rehypeAccessibleEmojis } from 'rehype-accessible-emojis';
{
markdown: {
rehypePlugins: [rehypeAccessibleEmojis]
}
}

类型:boolean
默认:true

¥Type: boolean
Default: true

Added in: astro@2.0.0

Astro 默认使用 GitHub 风格的 Markdown。要禁用此功能,请将 gfm 标志设置为 false

¥Astro uses GitHub-flavored Markdown by default. To disable this, set the gfm flag to false:

{
markdown: {
gfm: false,
}
}

类型:boolean
默认:true

¥Type: boolean
Default: true

Added in: astro@2.0.0

Astro 默认使用 SmartyPants 格式化程序。要禁用此功能,请将 smartypants 标志设置为 false

¥Astro uses the SmartyPants formatter by default. To disable this, set the smartypants flag to false:

{
markdown: {
smartypants: false,
}
}

类型:RemarkRehype

¥Type: RemarkRehype

将选项传递给 remark-rehype

¥Pass options to remark-rehype.

{
markdown: {
// Example: Translate the footnotes text to another language, here are the default English values
remarkRehype: { footnoteLabel: "Footnotes", footnoteBackLabel: "Back to reference 1"},
},
};

类型:object

¥Type: object

Added in: astro@3.5.0

配置 i18n 路由并允许你指定一些自定义选项。

¥Configures i18n routing and allows you to specify some customization options.

有关 Astro 的国际化 的更多信息,请参阅我们的指南

¥See our guide for more information on internationalization in Astro

类型:Locales

¥Type: Locales

Added in: astro@3.5.0

网站支持的所有语言环境的列表。这是一个必填字段。

¥A list of all locales supported by the website. This is a required field.

语言可以列为单独的代码(例如 ['en', 'es', 'pt-br']),也可以映射到共享的代码 path(例如 { path: "english", codes: ["en", "en-US"]})。这些代码将用于确定已部署站点的 URL 结构。

¥Languages can be listed either as individual codes (e.g. ['en', 'es', 'pt-br']) or mapped to a shared path of codes (e.g. { path: "english", codes: ["en", "en-US"]}). These codes will be used to determine the URL structure of your deployed site.

不强制执行特定的语言代码格式或语法,但包含内容文件的项目文件夹必须与列表中的 locales 项目完全匹配。如果有多个 codes 指向自定义 URL 路径前缀,请将内容文件存储在与配置的 path 同名的文件夹中。

¥No particular language code format or syntax is enforced, but your project folders containing your content files must match exactly the locales items in the list. In the case of multiple codes pointing to a custom URL path prefix, store your content files in a folder with the same name as the path configured.

类型:string

¥Type: string

Added in: astro@3.5.0

你的网站/应用的默认语言环境,即指定的 locales 之一。这是一个必填字段。

¥The default locale of your website/application, that is one of the specified locales. This is a required field.

没有强制执行特定的语言格式或语法,但我们建议根据需要使用小写字母和连字符(例如 “es”、“pt-br”)以获得最大兼容性。

¥No particular language format or syntax is enforced, but we suggest using lower-case and hyphens as needed (e.g. “es”, “pt-br”) for greatest compatibility.

类型:Record.<string, string>

¥Type: Record.<string, string>

Added in: astro@3.5.0

导航到不存在的页面(例如尚未创建翻译的页面)时的后备策略。

¥The fallback strategy when navigating to pages that do not exist (e.g. a translated page has not been created).

使用此对象为你支持的每种语言声明后备 locale 路由。如果未指定后备,则不可用页面将返回 404。

¥Use this object to declare a fallback locale route for each language you support. If no fallback is specified, then unavailable pages will return a 404.

¥Example

以下示例配置你的内容回退策略,以将 /pt-br/ 中不可用的页面重定向到 es 版本,并将 /fr/ 中不可用页面重定向到 en 版本。不可用的 /es/ 页面将返回 404。

¥The following example configures your content fallback strategy to redirect unavailable pages in /pt-br/ to their es version, and unavailable pages in /fr/ to their en version. Unavailable /es/ pages will return a 404.

export default defineConfig({
i18n: {
defaultLocale: "en",
locales: ["en", "fr", "pt-br", "es"],
fallback: {
pt: "es",
fr: "en"
}
}
})

类型:Routing

¥Type: Routing

Added in: astro@3.7.0

控制路由策略以确定你的站点 URL。根据默认语言的文件夹/URL 路径配置进行设置。

¥Controls the routing strategy to determine your site URLs. Set this based on your folder/URL path configuration for your default language.

i18n.routing.prefixDefaultLocale

标题部分 i18n.routing.prefixDefaultLocale

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@3.7.0

false 时,只有非默认语言才会显示语言前缀。defaultLocale 将不会显示语言前缀,并且本地化文件夹中不存在内容文件。对于所有非默认语言,URL 的格式为 example.com/[locale]/content/,但对于默认区域设置,URL 的格式为 example.com/content/

¥When false, only non-default languages will display a language prefix. The defaultLocale will not show a language prefix and content files do not exist in a localized folder. URLs will be of the form example.com/[locale]/content/ for all non-default languages, but example.com/content/ for the default locale.

true 时,所有 URL 都会显示语言前缀。每个路由的 URL 均采用 example.com/[locale]/content/ 形式,包括默认语言。本地化文件夹适用于每种语言,包括默认语言。

¥When true, all URLs will display a language prefix. URLs will be of the form example.com/[locale]/content/ for every route, including the default language. Localized folders are used for every language, including the default.

export default defineConfig({
i18n: {
defaultLocale: "en",
locales: ["en", "fr", "pt-br", "es"],
routing: {
prefixDefaultLocale: true,
}
}
})

i18n.routing.redirectToDefaultLocale

标题部分 i18n.routing.redirectToDefaultLocale

类型:boolean
默认:true

¥Type: boolean
Default: true

Added in: astro@4.2.0

配置在设置 prefixDefaultLocale: true 时,src/pages/index.astro 生成的主 URL (/) 是否重定向到 /[defaultLocale]

¥Configures whether or not the home URL (/) generated by src/pages/index.astro will redirect to /[defaultLocale] when prefixDefaultLocale: true is set.

设置 redirectToDefaultLocale: false 以在站点根目录禁用此自动重定向:

¥Set redirectToDefaultLocale: false to disable this automatic redirection at the root of your site:

astro.config.mjs
export default defineConfig({
i18n:{
defaultLocale: "en",
locales: ["en", "fr"],
routing: {
prefixDefaultLocale: true,
redirectToDefaultLocale: false
}
}
})

类型:"redirect" | "rewrite"
默认:"redirect"

¥Type: "redirect" | "rewrite"
Default: "redirect"

Added in: astro@4.15.0

i18n.fallback 配置为避免显示缺少页面路由的 404 页面时,此选项控制是 redirect 到后备页面,还是 rewrite 后备页面的内容。

¥When i18n.fallback is configured to avoid showing a 404 page for missing page routes, this option controls whether to redirect to the fallback page, or to rewrite the fallback page’s content in place.

默认情况下,Astro 的 i18n 路由会根据你的后备配置创建将访问者重定向到新目的地的页面。浏览器将刷新并在 URL 栏中显示目标地址。

¥By default, Astro’s i18n routing creates pages that redirect your visitors to a new destination based on your fallback configuration. The browser will refresh and show the destination address in the URL bar.

当配置 i18n.routing.fallback: "rewrite" 时,Astro 将创建在原始请求的 URL 上渲染后备页面内容的页面。

¥When i18n.routing.fallback: "rewrite" is configured, Astro will create pages that render the contents of the fallback page on the original, requested URL.

使用以下配置,如果你有文件 src/pages/en/about.astro 但没有 src/pages/fr/about.astro,则 astro build 命令将生成与 dist/en/about.html 页面内容相同的 dist/fr/about.html。你的网站访问者将在 https://example.com/fr/about/ 上看到页面的英文版本,并且不会被重定向。

¥With the following configuration, if you have the file src/pages/en/about.astro but not src/pages/fr/about.astro, the astro build command will generate dist/fr/about.html with the same content as the dist/en/about.html page. Your site visitor will see the English version of the page at https://example.com/fr/about/ and will not be redirected.

astro.config.mjs
export default defineConfig({
i18n: {
defaultLocale: "en",
locales: ["en", "fr"],
routing: {
prefixDefaultLocale: false,
fallbackType: "rewrite",
},
fallback: {
fr: "en",
}
},
})

类型:string

¥Type: string

Added in: astro@4.6.0

启用此选项后,Astro 将禁用其 i18n 中间件,以便你可以实现自己的自定义逻辑。不能使用 routing: "manual" 配置其他 routing 选项(例如 prefixDefaultLocale)。

¥When this option is enabled, Astro will disable its i18n middleware so that you can implement your own custom logic. No other routing options (e.g. prefixDefaultLocale) may be configured with routing: "manual".

你将负责编写自己的路由逻辑,或手动执行 Astro 的 i18n 中间件以及你自己的中间件。

¥You will be responsible for writing your own routing logic, or executing Astro’s i18n middleware manually alongside your own.

export default defineConfig({
i18n: {
defaultLocale: "en",
locales: ["en", "fr", "pt-br", "es"],
routing: {
prefixDefaultLocale: true,
}
}
})

类型:object
默认:{}

¥Type: object
Default: {}

Added in: astro@5.0.0

类型安全环境变量的配置选项。

¥Configuration options for type-safe environment variables.

有关 Astro 中的环境变量 的更多信息,请参阅我们的指南。

¥See our guide for more information on environment variables in Astro.

类型:EnvSchema
默认:{}

¥Type: EnvSchema
Default: {}

Added in: astro@5.0.0

使用 envField 定义环境变量的数据类型和属性的对象:context(客户端或服务器)、access(公开或秘密)、要使用的 default 值,以及此环境变量是否为 optional(默认为 false)。

¥An object that uses envField to define the data type and properties of your environment variables: context (client or server), access (public or secret), a default value to use, and whether or not this environment variable is optional (defaults to false).

astro.config.mjs
import { defineConfig, envField } from "astro/config"
export default defineConfig({
env: {
schema: {
API_URL: envField.string({ context: "client", access: "public", optional: true }),
PORT: envField.number({ context: "server", access: "public", default: 4321 }),
API_SECRET: envField.string({ context: "server", access: "secret" }),
}
}
})

envField 支持四种数据类型:字符串、数字、枚举和布尔值。contextaccess 是所有数据类型的必需属性。以下显示了每种数据类型可用的完整属性列表:

¥envField supports four data types: string, number, enum, and boolean. context and access are required properties for all data types. The following shows the complete list of properties available for each data type:

import { envField } from "astro/config"
envField.string({
// context & access
optional: true,
default: "foo",
max: 20,
min: 1,
length: 13,
url: true,
includes: "oo",
startsWith: "f",
endsWith: "o",
})
envField.number({
// context & access
optional: true,
default: 15,
gt: 2,
min: 1,
lt: 3,
max: 4,
int: true,
})
envField.boolean({
// context & access
optional: true,
default: true,
})
envField.enum({
// context & access
values: ['foo', 'bar', 'baz'], // required
optional: true,
default: 'baz',
})

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@5.0.0

启动开发服务器或运行构建时是否在服务器上验证密钥。

¥Whether or not to validate secrets on the server when starting the dev server or running a build.

默认情况下,启动开发服务器或构建时,仅在服务器上验证公共变量,仅在运行时验证私有变量。如果启用,还会在启动时检查私有变量。这在某些持续集成 (CI) 管道中很有用,可确保在部署之前正确设置所有密钥。

¥By default, only public variables are validated on the server when starting the dev server or a build, and private variables are validated at runtime only. If enabled, private variables will also be checked on start. This is useful in some continuous integration (CI) pipelines to make sure all your secrets are correctly set before deploying.

astro.config.mjs
import { defineConfig, envField } from "astro/config"
export default defineConfig({
env: {
schema: {
// ...
},
validateSecrets: true
}
})
Astro 中文网 - 粤ICP备13048890号