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' | 'hybrid'
默认:'static'

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

指定构建的输出目标。

¥Specifies the output target for builds.

  • 'static' - 构建一个可部署到任何静态主机的静态站点。

  • 'server' - 构建要部署到支持 SSR(服务器端渲染)的主机的应用。

  • 'hybrid' - 使用一些服务器端渲染的页面构建静态站点。

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 Server-side 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'
}
Terminal window
$ 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.

类型:object
默认:{}

¥Type: object
Default: {}

Added in: astro@4.9.0

为 Astro 网站启用安全措施。

¥Enables security measures for an Astro website.

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

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

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

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.9.0

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

¥When enabled, 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
默认:'./dist/client'

¥Type: string
Default: './dist/client'

仅当 output: 'server'output: 'hybrid' 时控制客户端 CSS 和 JavaScript 的输出目录。outDir 控制代码的构建位置。

¥Controls the output directory of your client-side CSS and JavaScript when output: 'server' or output: 'hybrid' only. outDir controls where the code is built to.

该值是相对于 outDir 的。

¥This value is relative to the outDir.

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

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

¥Type: string
Default: './dist/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 New

要并行构建的页面数。

¥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

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

¥Enable prefetching for links on your site to provide faster page transitions. (Enabled by default on pages using the <ViewTransitions /> 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 属性的链接。当使用 <ViewTransitions /> 路由时,该值默认为 true。否则,默认值为 false

¥Enable prefetching for all links, including those without the data-astro-prefetch attribute. This value defaults to true when using the <ViewTransitions /> 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

类型:string
默认:undefined

¥Type: string
Default: undefined

Added in: astro@3.1.0

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

¥Set the endpoint to use for image optimization in dev and SSR. Set to undefined to use the default endpoint.

端点将始终在 /_image 处注入。

¥The endpoint will always be injected at /_image.

{
image: {
// Example: Use a custom image endpoint
endpoint: './src/image-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

Section titled 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>
默认:[]

¥Type: Array.<string>
Default: []

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 值,如下所述。否则,只会配置提供的确切值:

¥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’)。

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

¥Markdown Options

类型:Partial<ShikiConfig>

¥Type: Partial<ShikiConfig>

Shiki 配置选项。使用方法请参见 Markdown 配置文档

¥Shiki configuration options. See the Markdown configuration docs for usage.

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

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

使用哪种语法荧光笔(如果有)。

¥Which syntax highlighter to use, if any.

  • shiki - 使用 志木 荧光笔

  • prism - 使用 Prisma 荧光笔

  • false - 不应用语法高亮。

{
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

类型:string

¥Type: string

Added in: astro@3.5.0

你的网站/应用的默认区域设置。这是一个必填字段。

¥The default locale of your website/application. 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.

类型:Locales

¥Type: Locales

Added in: astro@3.5.0

网站支持的所有区域设置的列表,包括 defaultLocale。这是一个必填字段。

¥A list of all locales supported by the website, including the defaultLocale. 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.

类型: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

Section titled 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

Section titled 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,
}
}
})

¥Legacy Flags

为了帮助某些用户在 Astro 版本之间迁移,我们偶尔会引入 legacy 标志。这些标志允许你选择加入最新版本中 Astro 的某些已弃用或过时的行为,以便你可以继续升级并利用新的 Astro 版本。

¥To help some users migrate between versions of Astro, we occasionally introduce legacy flags. These flags allow you to opt in to some deprecated or otherwise outdated behavior of Astro in the latest version, so that you can continue to upgrade and take advantage of new Astro releases.

¥Experimental Flags

Astro 提供实验性标志,让用户尽早访问新功能。不保证这些标志是稳定的。

¥Astro offers experimental flags to give users early access to new features. These flags are not guaranteed to be stable.

experimental.directRenderScript

Section titled experimental.directRenderScript

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.5.0

启用更可靠的策略以防止在未使用的页面中执行脚本。

¥Enables a more reliable strategy to prevent scripts from being executed in pages where they are not used.

脚本将直接按照 Astro 文件中声明的方式渲染(包括现有功能,如 TypeScript、导入 node_modules 和数据去重脚本)。你现在还可以有条件地在 Astro 文件中渲染脚本。但是,这意味着脚本不再提升到 <head>,页面上的多个脚本不再打包在一起。如果启用此选项,则应检查所有 <script> 标签是否按预期运行。

¥Scripts will directly render as declared in Astro files (including existing features like TypeScript, importing node_modules, and deduplicating scripts). You can also now conditionally render scripts in your Astro file. However, this means scripts are no longer hoisted to the <head> and multiple scripts on a page are no longer bundled together. If you enable this option, you should check that all your <script> tags behave as expected.

此选项将在 Astro 5.0 中默认启用。

¥This option will be enabled by default in Astro 5.0.

{
experimental: {
directRenderScript: true,
},
}

experimental.contentCollectionCache

Section titled experimental.contentCollectionCache

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@3.5.0

在静态模式下构建时启用内容集合的持久缓存。

¥Enables a persistent cache for content collections when building in static mode.

{
experimental: {
contentCollectionCache: true,
},
}

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.2.0

在受支持的浏览器中启用在客户端上预渲染预取页面。

¥Enables pre-rendering your prefetched pages on the client in supported browsers.

此功能使用实验性的 Speculation Rules Web API 并全局增强默认 prefetch 行为以在客户端上预渲染链接。你可能希望在启用此功能之前查看 在客户端预渲染时可能存在的风险

¥This feature uses the experimental Speculation Rules Web API and enhances the default prefetch behavior globally to prerender links on the client. You may wish to review the possible risks when prerendering on the client before enabling this feature.

在你的 astro.config.mjs 中启用客户端预渲染以及任何所需的 prefetch 配置选项:

¥Enable client side prerendering in your astro.config.mjs along with any desired prefetch configuration options:

astro.config.mjs
{
prefetch: {
prefetchAll: true,
defaultStrategy: 'viewport',
},
experimental: {
clientPrerender: true,
},
}

继续使用你网站上任何 <a /> 链接上的 data-astro-prefetch 属性来选择加入预取。不是将 <link> 标签附加到文档头部或使用 JavaScript 获取页面,而是将 <script> 标签附加到相应的推测规则。

¥Continue to use the data-astro-prefetch attribute on any <a /> link on your site to opt in to prefetching. Instead of appending a <link> tag to the head of the document or fetching the page with JavaScript, a <script> tag will be appended with the corresponding speculation rules.

客户端预渲染需要浏览器支持。如果不支持推测规则 API,prefetch 将回退到支持的策略。

¥Client side prerendering requires browser support. If the Speculation Rules API is not supported, prefetch will fallback to the supported strategy.

请参阅 预取指南 以了解更多 prefetch 选项和用法。

¥See the Prefetch Guide for more prefetch options and usage.

experimental.globalRoutePriority

Section titled experimental.globalRoutePriority

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.2.0

与基于文件的项目路由一样,优先考虑重定向和注入的路由,所有路由都遵循相同的 路由优先级顺序规则

¥Prioritizes redirects and injected routes equally alongside file-based project routes, following the same route priority order rules for all routes.

通过不自动优先考虑某些类型的路由,这允许更好地控制项目中的路由,并标准化所有路由的路由优先级顺序。

¥This allows more control over routing in your project by not automatically prioritizing certain types of routes, and standardizes the route priority ordering for all routes.

以下示例显示当基于文件的路由、注入的路由和重定向组合在一起时,哪个路由将构建某些页面 URL,如下所示:

¥The following example shows which route will build certain page URLs when file-based routes, injected routes, and redirects are combined as shown below:

  • 基于文件的路由:/blog/post/[pid]

  • 基于文件的路由:/[page]

  • Injected route:/blog/[...slug]

  • 重定向:/blog/tags/[tag] -> /[tag]

  • 重定向:/posts -> /blog

启用 experimental.globalRoutingPriority(而不是 Astro 4.0 默认路由优先级顺序):

¥With experimental.globalRoutingPriority enabled (instead of Astro 4.0 default route priority order):

  • /blog/tags/astro 由重定向到 /tags/[tag](而不是注入的路由 /blog/[...slug])构建

  • /blog/post/0 由基于文件的路由 /blog/post/[pid](而不是注入的路由 /blog/[...slug])构建

  • /posts 由重定向到 /blog(而不是基于文件的路由 /[page])构建

如果发生路由冲突,即两个具有相同路由优先级的路由尝试构建相同的 URL,Astro 将记录一条警告,以识别冲突的路由。

¥In the event of route collisions, where two routes of equal route priority attempt to build the same URL, Astro will log a warning identifying the conflicting routes.

类型:object
默认:undefined

¥Type: object
Default: undefined

Added in: astro@4.10.0

启用实验性 astro:env 功能。

¥Enables experimental astro:env features.

astro:env API 允许你为环境变量配置类型安全架构,并指示它们是否应在服务器或客户端上可用。从适当的 /client/server 模块导入并使用你定义的变量:

¥The astro:env API lets you configure a type-safe schema for your environment variables, and indicate whether they should be available on the server or the client. Import and use your defined variables from the appropriate /client or /server module:

---
import { API_URL } from "astro:env/client"
import { API_SECRET_TOKEN } from "astro:env/server"
const data = await fetch(`${API_URL}/users`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_SECRET_TOKEN}`
},
})
---
<script>
import { API_URL } from "astro:env/client"
fetch(`${API_URL}/ping`)
</script>

要定义环境变量的数据类型和属性,请在 experimental.env.schema 中的 Astro 配置中声明一个模式。envField 助手允许你将变量定义为字符串、数字或布尔值,并在对象中传递属性:

¥To define the data type and properties of your environment variables, declare a schema in your Astro config in experimental.env.schema. The envField helper allows you define your variable as a string, number, or boolean and pass properties in an object:

astro.config.mjs
import { defineConfig, envField } from "astro/config"
export default defineConfig({
experimental: {
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" }),
}
}
}
})

目前支持四种数据类型:字符串、数字、布尔值和枚举。

¥There are currently four data types supported: strings, numbers, booleans and enums.

有三种环境变量,由 env.schema 中定义的 context(客户端或服务器)和 access(秘密或公共)设置的组合决定:

¥There are three kinds of environment variables, determined by the combination of context (client or server) and access (secret or public) settings defined in your env.schema:

  • 公共客户端变量:这些变量最终会出现在你的最终客户端和服务器包中,并且可以通过 astro:env/client 模块从客户端和服务器访问:

    import { API_URL } from "astro:env/client"
  • 公共服务器变量:这些变量最终会出现在你的最终服务器包中,并且可以通过 astro:env/server 模块在服务器上访问:

    import { PORT } from "astro:env/server"
  • 秘密服务器变量:这些变量不是最终打包包的一部分,可以通过 astro:env/server 模块在服务器上访问。getSecret() 辅助函数可用于检索架构中未指定的密钥。它的实现由你的适配器提供,默认为 process.env

    import { API_SECRET, getSecret } from "astro:env/server"
    const SECRET_NOT_IN_SCHEMA = getSecret("SECRET_NOT_IN_SCHEMA") // string | undefined

注意:不支持秘密客户端变量,因为没有安全的方法将这些数据发送到客户端。因此,无法在你的架构中同时配置 context: "client"access: "secret"

¥Note: Secret client variables are not supported because there is no safe way to send this data to the client. Therefore, it is not possible to configure both context: "client" and access: "secret" in your schema.

有关完整概述以及对此实验性 API 提供反馈,请参阅 Astro Env RFC

¥For a complete overview, and to give feedback on this experimental API, see the Astro Env RFC.

类型:EnvSchema
默认:undefined

¥Type: EnvSchema
Default: undefined

Added in: astro@4.10.0

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

¥An object that uses envField to define the data type (string, number, or boolean) 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({
experimental: {
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" }),
}
}
}
})

experimental.env.validateSecrets

Section titled experimental.env.validateSecrets

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.11.6

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

¥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({
experimental: {
env: {
schema: {
// ...
},
validateSecrets: true
}
}
})

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.12.0

启用实验性服务器岛功能。Server Islands 提供了在页面已经渲染后延迟组件异步渲染的能力。

¥Enables experimental Server Island features. Server Islands offer the ability to defer a component to render asynchronously after the page has already rendered.

要启用,请使用适配器配置 按需服务器渲染 output 模式,并将 serverIslands 标志添加到 experimental 对象:

¥To enable, configure an on-demand server rendering output mode with an adapter, and add the serverIslands flag to the experimental object:

{
output: 'hybrid', // or 'server'
adapter: nodejs({ mode: 'standalone' }),
experimental: {
serverIslands: true,
},
}

在任何 Astro 组件上使用 server:defer 指令来延迟初始渲染:

¥Use the server:defer directive on any Astro component to delay initial rendering:

---
import Avatar from '~/components/Avatar.astro';
---
<Avatar server:defer />

外部页面将在构建时(hybrid)或运行时(server)渲染,其中省略群岛内容并在其位置包含 <script> 标签。

¥The outer page will be rendered, either at build time (hybrid) or at runtime (server) with the island content omitted and a <script> tag included in its place.

页面在浏览器中加载后,脚本标记将通过发出请求将其自身替换为岛的内容。

¥After the page loads in the browser, the script tag will replace itself with the contents of the island by making a request.

任何 Astro 组件都可以被赋予 server: defer 属性以延迟其渲染。没有特殊的 API,你可以像往常一样编写 .astro 代码:

¥Any Astro component can be given the server: defer attribute to delay its rendering. There is no special API and you can write .astro code as normal:

---
import { getUser } from '../api';
const user = await getUser(Astro.locals.userId);
---
<img class="avatar" src={user.imageUrl}>

¥Server island fallback content

由于你的组件不会与页面的其余部分一起渲染,你可能需要添加通用内容(例如加载消息)以暂时显示在其位置。此内容将在页面首次渲染时但在岛加载之前显示。

¥Since your component will not render with the rest of the page, you may want to add generic content (e.g. a loading message) to temporarily show in its place. This content will be displayed when the page first renders but before the island has loaded.

使用 slot="fallback" 属性将占位符内容添加为 Astro 组件的子项。当你的群岛内容可用时,后备内容将被替换。

¥Add placeholder content as a child of your Astro component with the slot="fallback" attribute. When your island content is available, the fallback content will be replaced.

以下示例将通用头像显示为后备内容,然后使用视图转换动画化为个性化头像:

¥The example below displays a generic avatar as fallback content, then animates into a personalized avatar using view transitions:

<Avatar server:defer>
<svg slot="fallback" class="generic-avatar" transition:name="avatar">...</svg>
</Avatar>

有关完整概述以及对此实验性 API 提供反馈,请参阅 Server Islands RFC

¥For a complete overview, and to give feedback on this experimental API, see the Server Islands RFC.

experimental.contentIntellisense

Section titled experimental.contentIntellisense

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.14.0

在兼容编辑器中为你的内容集合条目启用 Intellisense 功能(例如代码完成、快速提示)。

¥Enables Intellisense features (e.g. code completion, quick hints) for your content collection entries in compatible editors.

启用后,此功能将生成 JSON 架构并将其添加到项目中的 .astro 目录中。Astro 语言服务器可以使用这些文件在内容文件(.md.mdx.mdoc)内提供 Intellisense。

¥When enabled, this feature will generate and add JSON schemas to the .astro directory in your project. These files can be used by the Astro language server to provide Intellisense inside content files (.md, .mdx, .mdoc).

{
experimental: {
contentIntellisense: true,
},
}

要将此功能与 Astro VS Code 扩展一起使用,你还必须在 VS Code 设置中启用 astro.content-intellisense 选项。对于直接使用 Astro 语言服务器的编辑器,请传递 contentIntellisense: true 初始化参数以启用此功能。有关此早期功能的更多详细信息,请参阅 内容 Intellisense 实现 PR

¥To use this feature with the Astro VS Code extension, you must also enable the astro.content-intellisense option in your VS Code settings. For editors using the Astro language server directly, pass the contentIntellisense: true initialization parameter to enable this feature. See the content Intellisense implementation PR for more details about this early feature.

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@4.14.0

内容层 API 是一种在 Astro 中处理内容和数据的新方法。它类似于 内容集合 并建立在 内容集合 之上,将它们超越 src/content/ 中的本地文件,并允许你从任何地方获取内容,包括远程 API,方法是将 loader 添加到你的集合中。

¥The Content Layer API is a new way to handle content and data in Astro. It is similar to and builds upon content collections, taking them beyond local files in src/content/ and allowing you to fetch content from anywhere, including remote APIs, by adding a loader to your collection.

你的现有内容集合可以通过一些小的更改成为 迁移到内容层 API。但是,没有必要一次更新所有集合来添加由内容层 API 支持的新集合。你可能同时拥有使用 src/content/config.ts 中定义的现有和新 API 的集合。

¥Your existing content collections can be migrated to the Content Layer API with a few small changes. However, it is not necessary to update all your collections at once to add a new collection powered by the Content Layer API. You may have collections using both the existing and new APIs defined in src/content/config.ts at the same time.

内容层 API 旨在功能更强大、性能更佳,帮助网站扩展到数千个页面。数据在构建之间缓存并逐步更新。Markdown 解析速度也提高了 5-10 倍,内存减少幅度也类似,MDX 速度提高了 2-3 倍。

¥The Content Layer API is designed to be more powerful and more performant, helping sites scale to thousands of pages. Data is cached between builds and updated incrementally. Markdown parsing is also 5-10 times faster, with similar scale reductions in memory, and MDX is 2-3 times faster.

要启用,请将 contentLayer 标志添加到 Astro 配置中的 experimental 对象:

¥To enable, add the contentLayer flag to the experimental object in your Astro config:

astro.config.mjs
{
experimental: {
contentLayer: true,
}
}

¥Fetching data with a loader

内容层 API 允许你从 src/content/ 文件夹外部获取内容(无论是本地存储在项目中还是远程存储),并使用 loader 属性检索数据。

¥The Content Layer API allows you to fetch your content from outside of the src/content/ folder (whether stored locally in your project or remotely) and uses a loader property to retrieve your data.

loader 在集合的架构中定义,并返回一个条目数组。Astro 提供两个内置加载器函数(glob()file())用于获取你的本地内容,以及访问 构建你自己的加载器并获取远程数据 的 API。

¥The loader is defined in the collection’s schema and returns an array of entries. Astro provides two built-in loader functions (glob() and file()) for fetching your local content, as well as access to the API to construct your own loader and fetch remote data.

glob() 加载器从文件系统上任何位置的 Markdown、MDX、Markdoc 或 JSON 文件的目录中创建条目。它接受要匹配的条目文件的 pattern,以及文件所在位置的 base 文件路径。当每个条目有一个文件时,请使用此功能。

¥The glob() loader creates entries from directories of Markdown, MDX, Markdoc, or JSON files from anywhere on the filesystem. It accepts a pattern of entry files to match, and a base file path of where your files are located. Use this when you have one file per entry.

file() 加载器从单个本地文件创建多个条目。当你的所有条目都存储在对象数组中时,请使用此功能。

¥The file() loader creates multiple entries from a single local file. Use this when all your entries are stored in an array of objects.

src/content/config.ts
import { defineCollection, z } from 'astro:content';
import { glob, file } from 'astro/loaders';
const blog = defineCollection({
// By default the ID is a slug generated from
// the path of the file relative to `base`
loader: glob({ pattern: "**\/*.md", base: "./src/data/blog" }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
})
});
const dogs = defineCollection({
// The path is relative to the project root, or an absolute path.
loader: file("src/data/dogs.json"),
schema: z.object({
id: z.string(),
breed: z.string(),
temperament: z.array(z.string()),
}),
});
export const collections = { blog, dogs };

使用内容层 API 查询和渲染

Section titled 使用内容层 API 查询和渲染

¥Querying and rendering with the Content Layer API

集合可以是 以与内容集合相同的方式查询

¥The collection can be queried in the same way as content collections:

src/pages/index.astro
import { getCollection, getEntry } from 'astro:content';
// Get all entries from a collection.
// Requires the name of the collection as an argument.
const allBlogPosts = await getCollection('blog');
// Get a single entry from a collection.
// Requires the name of the collection and ID
const labradorData = await getEntry('dogs', 'labrador-retriever');

可以使用 render() 函数将从 Markdown、MDX 或 Markdoc 生成的条目直接渲染到页面。

¥Entries generated from Markdown, MDX, or Markdoc can be rendered directly to a page using the render() function.

src/pages/[slug].astro
---
import { getEntry, render } from 'astro:content';
const post = await getEntry('blog', Astro.params.slug);
const { Content, headings } = await render(post);
---
<Content />

¥Creating a loader

使用内容层 API,你可以构建加载器以从任何地方加载或生成内容。

¥With the Content Layer API, you can build loaders to load or generate content from anywhere.

例如,你可以创建一个从远程 API 获取集合条目的加载器。

¥For example, you can create a loader that fetches collection entries from a remote API.

src/content/config.ts
const countries = defineCollection({
loader: async () => {
const response = await fetch("https://restcountries.com/v3.1/all");
const data = await response.json();
// Must return an array of entries with an id property,
// or an object with IDs as keys and entries as values
return data.map((country) => ({
id: country.cca3,
...country,
}));
},
// optionally add a schema
// schema: z.object...
});
export const collections = { countries };

对于更高级的加载逻辑,你可以定义一个对象加载器。这允许增量更新和条件加载,同时还提供对数据存储的完全访问权限。请参阅 内容层 API RFC 中的 API。

¥For more advanced loading logic, you can define an object loader. This allows incremental updates and conditional loading while also giving full access to the data store. See the API in the Content Layer API RFC.

迁移现有内容集合以使用内容层 API

Section titled 迁移现有内容集合以使用内容层 API

¥Migrating an existing content collection to use the Content Layer API

你可以将具有 Markdown、MDX、Markdoc 或 JSON 条目的现有内容集合转换为使用内容层 API。

¥You can convert an existing content collection with Markdown, MDX, Markdoc, or JSON entries to use the Content Layer API.

  1. 将集合文件夹移出 src/content/(例如移到 src/data/)。位于 src/content/ 文件夹中的所有集合都将使用现有的内容集合 API。

    不要移动现有的 src/content/config.ts 文件。此文件将使用任一 API 定义所有集合。

  2. 编辑集合定义。你更新的集合需要 loader,并且选择集合 type 的选项不再可用。

    src/content/config.ts
    import { defineCollection, z } from 'astro:content';
    import { glob } from 'astro/loaders';
    const blog = defineCollection({
    // For content layer you no longer define a `type`
    type: 'content',
    loader: glob({ pattern: '**\/[^_]*.md', base: "./src/data/blog" }),
    schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
    }),
    });
  3. 将引用从 slug 更改为 id。内容层集合没有 slug 字段。相反,所有更新的集合都将有一个 id

    src/pages/index.astro
    ---
    export async function getStaticPaths() {
    const posts = await getCollection('blog');
    return posts.map((post) => ({
    params: { slug: post.slug },
    params: { slug: post.id },
    props: post,
    }));
    }
    ---
  4. 切换到新的 render() 功能。条目不再具有 render() 方法,因为它们现在是可序列化的普通对象。相反,从 astro:content 导入 render() 函数。

    src/pages/index.astro
    ---
    import { getEntry } from 'astro:content';
    import { getEntry, render } from 'astro:content';
    const post = await getEntry('blog', params.slug);
    const { Content, headings } = await post.render();
    const { Content, headings } = await render(post);
    ---
    <Content />

¥Learn more

有关完整概述和完整的 API 参考,请参阅 内容层 API RFC分享你的反馈

¥For a complete overview and the full API reference, see the Content Layer API RFC and share your feedback.

Astro 中文网 - 粤ICP备13048890号