Astro 集成 API
Astro Integrations 仅需几行代码即可为你的项目添加新功能和行为。
¥Astro Integrations add new functionality and behaviors for your project with only a few lines of code.
此参考页适用于编写自己的集成的任何人。要了解如何在项目中使用集成,请查看我们的 使用集成 指南。
¥This reference page is for anyone writing their own integration. To learn how to use an integration in your project, check out our Using Integrations guide instead.
¥Examples
当你构建自己的集成时,官方 Astro 集成可以作为你的参考。
¥The official Astro integrations can act as reference for you as you go to build your own integrations.
快速 API 参考
Section titled 快速 API 参考¥Quick API Reference
¥Hooks
Astro 提供集成可以实现的钩子,以在 Astro 生命周期的某些部分执行。Astro 钩子在 IntegrationHooks
接口中定义,它是全局 Astro
命名空间的一部分。
¥Astro provides hooks that integrations can implement to execute during certain parts of Astro’s lifecycle. Astro hooks are defined in the IntegrationHooks
interface, which is part of the global Astro
namespace.
Astro 内置了以下钩子:
¥The following hooks are built in to Astro:
astro:config:setup
Section titled astro:config:setup下一个钩子:astro:config:done
¥Next hook: astro:config:done
什么时候:初始化时,在 Vite 或 Astro 配置 解析之前。
¥When: On initialization, before either the Vite or Astro config have resolved.
为什么:扩展项目配置。这包括更新 Astro 配置、应用 Vite 插件、添加组件渲染器以及将脚本注入到页面上。
¥Why: To extend the project config. This includes updating the Astro config, applying Vite plugins, adding component renderers, and injecting scripts onto the page.
config
选项
Section titled config 选项¥config
option
类型:AstroConfig
¥Type: AstroConfig
用户提供的 Astro 配置 的只读副本。在运行任何其他集成之前,此问题已得到解决。如果你在所有集成完成其配置更新后需要配置副本,参见 astro:config:done
钩子.
¥A read-only copy of the user-supplied Astro config. This is resolved before any other integrations have run. If you need a copy of the config after all integrations have completed their config updates, see the astro:config:done
hook.
command
选项
Section titled command 选项¥command
option
类型:'dev' | 'build' | 'preview' | 'sync'
¥Type: 'dev' | 'build' | 'preview' | 'sync'
-
dev
- 项目使用astro dev
执行 -
build
- 项目使用astro build
执行 -
preview
- 项目使用astro preview
执行 -
sync
- 项目使用astro sync
执行
isRestart
选项
Section titled isRestart 选项¥isRestart
option
类型:boolean
¥Type: boolean
false
当开发服务器启动时,true
当触发重新加载时。用于检测何时多次调用此函数。
¥false
when the dev server starts, true
when a reload is triggered. Useful to detect when this function is called more than once.
updateConfig
选项
Section titled updateConfig 选项¥updateConfig
option
类型:(newConfig: DeepPartial<AstroConfig>) => AstroConfig;
¥Type: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
用于更新用户提供的 Astro 配置 的回调函数。你提供的任何配置都将与用户配置 + 其他集成配置更新合并,因此你可以随意省略键!
¥A callback function to update the user-supplied Astro config. Any config you provide will be merged with the user config + other integration config updates, so you are free to omit keys!
例如,假设你需要向用户的项目提供 Vite 插件:
¥For example, say you need to supply a Vite plugin to the user’s project:
addRenderer
选项
Section titled addRenderer 选项¥addRenderer
option
类型:(renderer:
AstroRenderer
) => void;
示例:lit
, svelte
, react
, preact
, vue
, solid
¥Type: (renderer:
AstroRenderer
) => void;
Examples: lit
, svelte
, react
, preact
, vue
, solid
用于添加组件框架渲染器(即 React、Vue、Svelte 等)的回调函数。你可以浏览上面的示例和类型定义以获取更高级的选项,但以下是需要注意的 2 个主要选项:
¥A callback function to add a component framework renderer (i.e. React, Vue, Svelte, etc). You can browse the examples and type definition above for more advanced options, but here are the 2 main options to be aware of:
-
clientEntrypoint
- 每当使用组件时在客户端上执行的文件的路径。这主要是为了用 JS 渲染或滋润你的组件。 -
serverEntrypoint
- 每当使用组件时,在服务器端请求或静态构建期间执行的文件的路径。这些应该将组件渲染为静态标记,并在适用的情况下使用用于水合作用的钩子。React 的renderToString
回调 就是一个典型的例子。
addWatchFile
选项
Section titled addWatchFile 选项¥addWatchFile
option
类型:URL | string
¥Type: URL | string
如果你的集成依赖于 Vite 不监视的某些配置文件和/或需要完整的开发服务器重新启动才能生效,请使用 addWatchFile
添加它。每当该文件发生更改时,Astro 开发服务器都会重新加载(你可以使用 isRestart
检查何时重新加载)。
¥If your integration depends on some configuration file that Vite doesn’t watch and/or needs a full dev server restart to take effect, add it with addWatchFile
. Whenever that file changes, the Astro dev server will be reloaded (you can check when a reload happens with isRestart
).
用法示例:
¥Example usage:
addClientDirective
选项
Section titled addClientDirective 选项¥addClientDirective
option
Added in:
astro@2.6.0
类型:(directive:
ClientDirectiveConfig
) => void;
¥Type: (directive:
ClientDirectiveConfig
) => void;
添加要在 .astro
文件中使用的 自定义客户端指令。
¥Adds a custom client directive to be used in .astro
files.
请注意,指令入口点仅通过 esbuild 打包,并且应保持较小,这样它们就不会减慢组件的水合速度。
¥Note that directive entrypoints are only bundled through esbuild and should be kept small so they don’t slow down component hydration.
用法示例:
¥Example usage:
你还可以在库的类型定义文件中添加指令的类型:
¥You can also add types for the directives in your library’s type definition file:
addDevToolbarApp
选项
Section titled addDevToolbarApp 选项¥addDevToolbarApp
option
Added in:
astro@3.4.0
类型:(pluginEntrypoint: string) => void;
¥Type: (pluginEntrypoint: string) => void;
添加 自定义开发工具栏应用。
¥Adds a custom dev toolbar app.
用法示例:
¥Example usage:
addMiddleware
选项
Section titled addMiddleware 选项¥addMiddleware
option
Added in:
astro@3.5.0
类型:(middleware:
AstroIntegrationMiddleware
) => void;
¥Type: (middleware:
AstroIntegrationMiddleware
) => void;
添加 中间件 以针对每个请求运行。采用包含中间件的 entrypoint
模块和 order
来指定它是应该在其他中间件之前 (pre
) 还是之后 (post
) 运行。
¥Adds middleware to run on each request. Takes the entrypoint
module that contains the middleware, and an order
to specify whether it should run before (pre
) other middleware or after (post
).
中间件是在具有 onRequest
函数的包中定义的,与用户定义的中间件一样。
¥Middleware is defined in a package with an onRequest
function, as with user-defined middleware.
injectRoute
选项
Section titled injectRoute 选项¥injectRoute
option
类型:({ pattern: string, entrypoint: string }) => void;
¥Type: ({ pattern: string, entrypoint: string }) => void;
用于将路由注入 Astro 项目的回调函数。注入的路由可以是 .astro
页 或 .js
和 .ts
路由处理程序。
¥A callback function to inject routes into an Astro project. Injected routes can be .astro
pages or .js
and .ts
route handlers.
injectRoute
接受一个带有 pattern
和 entrypoint
的对象。
¥injectRoute
takes an object with a pattern
and an entrypoint
.
-
pattern
- 其中浏览器中应输出路由,例如/foo/bar
。pattern
可以使用 Astro 的文件路径语法来表示动态路由,例如/foo/[bar]
或/foo/[...bar]
。请注意,pattern
中不需要文件扩展名。 -
entrypoint
- 指向.astro
页面或.js
/.ts
路由处理程序的裸模块说明符,用于处理pattern
中表示的路由。
¥Example usage
对于设计为安装在其他项目中的集成,请使用其包名称来引用路由入口点。以下示例显示了作为 @fancy/dashboard
注入仪表板路由的包发布到 npm:
¥For an integration designed to be installed in other projects, use its package name to refer to the route entrypoint.
The following example shows a package published to npm as @fancy/dashboard
injecting a dashboard route:
将你的包(本例中为 @fancy/dashboard
)发布到 npm 时,你必须在 package.json
中导出 dashboard.astro
:
¥When publishing your package (@fancy/dashboard
, in this case) to npm, you must export dashboard.astro
in your package.json
:
injectScript
选项
Section titled injectScript 选项¥injectScript
option
类型:(stage: InjectedScriptStage, content: string) => void;
¥Type: (stage: InjectedScriptStage, content: string) => void;
用于将 JavaScript 内容字符串注入每个页面的回调函数。
¥A callback function to inject a string of JavaScript content onto every page.
stage
表示应如何插入该脚本(content
)。有些阶段允许插入脚本而无需修改,而其他阶段则允许在 Vite 的打包步骤 期间进行优化:
¥The stage
denotes how this script (the content
) should be inserted. Some stages allow inserting scripts without modification, while others allow optimization during Vite’s bundling step:
-
"head-inline"
:注入到每个页面的<head>
中的脚本标记中。Vite 未对其进行优化或解析。 -
"before-hydration"
:在水合脚本运行之前导入客户端。已由 Vite 优化解决。 -
"page"
:与head-inline
类似,不同之处在于注入的代码片段由 Vite 处理,并与页面上 Astro 组件内定义的任何其他<script>
标签打包在一起。该脚本将在最终页面输出中加载<script type="module">
,并由 Vite 优化和解析。 -
"page-ssr"
:在每个 Astro 页面组件的 frontmatter 中作为单独的模块导入。由于此阶段导入你的脚本,因此Astro
全局不可用,并且你的脚本仅在首次评估import
时运行一次。page-ssr
阶段的主要用途是在每个页面中注入一个 CSSimport
,供 Vite 优化解析:
astro:config:done
Section titled astro:config:done上一个钩子:astro:config:setup
¥Previous hook: astro:config:setup
下一个钩子:在 “dev” 模式下运行时为 astro:server:setup
,或在生产构建期间为 astro:build:start
¥Next hook: astro:server:setup
when running in “dev” mode, or astro:build:start
during production builds
什么时候:在 Astro 配置已解决并且其他集成已运行其 astro:config:setup
钩子后。
¥When: After the Astro config has resolved and other integrations have run their astro:config:setup
hooks.
为什么:检索最终配置以在其他钩子中使用。
¥Why: To retrieve the final config for use in other hooks.
config
选项
Section titled config 选项¥config
option
类型:AstroConfig
¥Type: AstroConfig
用户提供的 Astro 配置 的只读副本。其他集成运行后此问题即可解决。
¥A read-only copy of the user-supplied Astro config. This is resolved after other integrations have run.
setAdapter
选项
Section titled setAdapter 选项¥setAdapter
option
类型:(adapter: AstroAdapter) => void;
¥Type: (adapter: AstroAdapter) => void;
使集成成为适配器。在 适配器 API 中阅读更多内容。
¥Makes the integration an adapter. Read more in the adapter API.
injectTypes
选项
Section titled injectTypes 选项¥injectTypes
options
Added in:
astro@4.14.0
类型:(injectedType: { filename: string; content: string }) => URL
¥Type: (injectedType: { filename: string; content: string }) => URL
允许你通过添加新的 *.d.ts
文件将类型注入用户的项目中。
¥Allows you to inject types into your user’s project by adding a new *.d.ts
file.
filename
属性将用于在 /.astro/integrations/<normalized_integration_name>/<normalized_filename>.d.ts
处生成文件,并且必须以 ".d.ts"
结尾。
¥The filename
property will be used to generate a file at /.astro/integrations/<normalized_integration_name>/<normalized_filename>.d.ts
and must end with ".d.ts"
.
content
属性将创建文件的主体,并且必须是有效的 TypeScript。
¥The content
property will create the body of the file and must be valid TypeScript.
此外,injectTypes()
返回指向规范化路径的 URL,以便你以后可以覆盖其内容,或以任何你想要的方式对其进行操作。
¥Additionally, injectTypes()
returns a URL to the normalized path so you can overwrite its content later on, or manipulate it in any way you want.
astro:server:setup
Section titled astro:server:setup上一个钩子:astro:config:done
¥Previous hook: astro:config:done
下一个钩子:astro:server:start
¥Next hook: astro:server:start
什么时候:就在 “dev” 模式下创建 Vite 服务器之后,但在 listen()
事件触发之前。参见 Vite 的 createServer API 了解更多。
¥When: Just after the Vite server is created in “dev” mode, but before the listen()
event is fired. See Vite’s createServer API for more.
为什么:更新 Vite 服务器选项和中间件。
¥Why: To update Vite server options and middleware.
server
选项
Section titled server 选项¥server
option
¥Type: ViteDevServer
“dev” 模式下使用的 Vite 服务器的可变实例。例如,这是 由我们的 Partytown 集成使用 将 Partytown 服务器作为中间件注入:
¥A mutable instance of the Vite server used in “dev” mode. For instance, this is used by our Partytown integration to inject the Partytown server as middleware:
astro:server:start
Section titled astro:server:start上一个钩子:astro:server:setup
¥Previous hook: astro:server:setup
下一个钩子:astro:server:done
¥Next hook: astro:server:done
什么时候:就在服务器的 listen()
事件触发之后。
¥When: Just after the server’s listen()
event has fired.
为什么:拦截指定地址的网络请求。如果你打算将此地址用于中间件,请考虑使用 astro:server:setup
。
¥Why: To intercept network requests at the specified address. If you intend to use this address for middleware, consider using astro:server:setup
instead.
address
选项
Section titled address 选项¥address
option
类型:AddressInfo
¥Type: AddressInfo
Node.js Net 模块 提供的地址、系列和端口号。
¥The address, family and port number supplied by the Node.js Net module.
astro:server:done
Section titled astro:server:done上一个钩子:astro:server:start
¥Previous hook: astro:server:start
什么时候:就在开发服务器关闭之后。
¥When: Just after the dev server is closed.
为什么:要运行你可能在 astro:server:setup
或 astro:server:start
钩子期间触发的任何清理事件。
¥Why: To run any cleanup events you may trigger during the astro:server:setup
or astro:server:start
hooks.
astro:build:start
Section titled astro:build:start上一个钩子:astro:config:done
¥Previous hook: astro:config:done
下一个钩子:astro:build:setup
¥Next hook: astro:build:setup
什么时候:在 astro:config:done
事件之后,但在生产构建开始之前。
¥When: After the astro:config:done
event, but before the production build begins.
为什么:设置生产构建期间所需的任何全局对象或客户端。这还可以扩展 适配器 API 中的构建配置选项。
¥Why: To set up any global objects or clients needed during a production build. This can also extend the build configuration options in the adapter API.
astro:build:setup
Section titled astro:build:setup上一个钩子:astro:build:start
¥Previous hook: astro:build:start
下一个钩子:astro:build:ssr
¥Next hook: astro:build:ssr
什么时候:在 astro:build:start
钩子之后,在构建之前立即运行。
¥When: After the astro:build:start
hook, runs immediately before the build.
为什么:至此,构建的 Vite 配置已经完全构建完成,这是你修改它的最后机会。例如,这对于覆盖某些默认值很有用。如果你不确定是否应该使用此钩子或 astro:build:start
,请改用 astro:build:start
。
¥Why: At this point, the Vite config for the build has been completely constructed, this is your final chance to modify it. This can be useful for example to overwrite some defaults. If you’re not sure whether you should use this hook or astro:build:start
, use astro:build:start
instead.
astro:build:generated
Section titled astro:build:generated上一个钩子:astro:build:setup
¥Previous hook: astro:build:setup
什么时候:静态生产构建完成生成路由和资源后。
¥When: After a static production build has finished generating routes and assets.
为什么:要在清理构建工件之前访问生成的路由和资源。这是一个非常不常见的用例。我们建议使用 astro:build:done
,除非你确实需要在清理之前访问生成的文件。
¥Why: To access generated routes and assets before build artifacts are cleaned up. This is a very uncommon use case. We recommend using astro:build:done
unless you really need to access the generated files before cleanup.
astro:build:ssr
Section titled astro:build:ssr上一个钩子:astro:build:setup
¥Previous hook: astro:build:setup
什么时候:生产 SSR 构建完成后。
¥When: After a production SSR build has completed.
为什么:访问 SSR 清单和发出的入口点的映射。在插件或集成中创建自定义 SSR 构建时,这非常有用。
¥Why: To access the SSR manifest and map of the emitted entry points. This is useful when creating custom SSR builds in plugins or integrations.
-
entryPoints
将页面路由映射到构建后发出的物理文件; -
middlewareEntryPoint
为中间件文件的文件系统路径;
astro:build:done
Section titled astro:build:done上一个钩子:astro:build:ssr
¥Previous hook: astro:build:ssr
什么时候:生产构建(SSG 或 SSR)完成后。
¥When: After a production build (SSG or SSR) has completed.
为什么:访问生成的路由和资源以进行扩展(例如,将内容复制到生成的 /assets
目录中)。如果你计划转换生成的资源,我们建议你探索 Vite 插件 API 和 通过 astro:config:setup
配置。
¥Why: To access generated routes and assets for extension (ex. copy content into the generated /assets
directory). If you plan to transform generated assets, we recommend exploring the Vite Plugin API and configuring via astro:config:setup
instead.
dir
选项
Section titled dir 选项¥dir
option
类型:URL
¥Type: URL
构建输出目录的 URL 路径。请注意,如果你需要有效的绝对路径字符串,则应使用 Node 的内置 fileURLToPath
实用程序。
¥A URL path to the build output directory. Note that if you need a valid absolute path string, you should use Node’s built-in fileURLToPath
utility.
routes
选项
Section titled routes 选项¥routes
option
类型:RouteData[]
¥Type: RouteData[]
所有生成的路由及其关联元数据的列表。
¥A list of all generated routes alongside their associated metadata.
你可以参考下面的完整 RouteData
类型,但最常见的属性是:
¥You can reference the full RouteData
type below, but the most common properties are:
-
component
- 相对于项目根目录的输入文件路径 -
pathname
- 输出文件 URL(对于使用[dynamic]
和[...spread]
参数的路由未定义)
RouteData
型号参考
Section titled RouteData 型号参考¥RouteData
type reference
pages
选项
Section titled pages 选项¥pages
option
类型:{ pathname: string }[]
¥Type: { pathname: string }[]
所有生成的页面的列表。它是一个具有一个属性的对象。
¥A list of all generated pages. It is an object with one property.
pathname
- 页面的最终路径。
astro:route:setup
Section titled astro:route:setup
Added in:
astro@4.14.0
什么时候:在 astro dev
中,每当请求路由时。在 astro build
中,在打包和转换路由文件时。
¥When: In astro dev
, whenever a route is requested. In astro build
, while bundling and transforming a route file.
为什么:要在构建或请求时设置路由选项,例如启用 按需服务器渲染。
¥Why: To set options for a route at build or request time, such as enabling on-demand server rendering.
route
选项
Section titled route 选项¥route
option
类型:RouteOptions
¥Type: RouteOptions
一个具有 component
属性的对象,用于标识路由和以下附加值,以允许你配置生成的路由:prerender
。
¥An object with a component
property to identify the route and the following additional values to allow you to configure the generated route: prerender
.
component
属性是相对于项目根目录的只读字符串路径,例如 "src/pages/blog/[slug].astro"
。
¥The component
property is a readonly string path relative to the project root, e.g "src/pages/blog/[slug].astro"
.
route.prerender
Section titled route.prerender类型:boolean
默认:undefined
¥Type: boolean
Default: undefined
astro@4.14.0
prerender
属性用于为路由配置 按需服务器渲染。如果路由文件包含显式 export const prerender
值,则该值将用作默认值,而不是 undefined
。
¥The prerender
property is used to configure on-demand server rendering for a route. If the route file contains an explicit export const prerender
value, the value will be used as the default instead of undefined
.
如果运行完所有钩子之后的最终值是 undefined
,则路由将基于 output
选项 回退到预渲染默认值:为 hybrid
模式预渲染,为 server
模式按需渲染。
¥If the final value after running all the hooks is undefined
, the route will fall back to a prerender default based on the output
option: prerendered for hybrid
mode, and on-demand rendered for server
mode.
自定义钩子
Section titled 自定义钩子¥Custom hooks
可以通过 全局增强 扩展 IntegrationHooks
接口,将自定义钩子添加到集成中。
¥Custom hooks can be added to integrations by extending the IntegrationHooks
interface through global augmentation.
Astro 为未来的内置钩子保留了 astro:
前缀。命名自定义钩子时,请选择不同的前缀。
¥Astro reserves the astro:
prefix for future built-in hooks. Please choose a different prefix when naming your custom hook.
HookParameters
Section titled HookParameters你可以通过将钩子的名称传递给 HookParameters
工具类型来获取钩子参数的类型。在以下示例中,函数的 options
参数被输入以匹配 astro:config:setup
钩子的参数:
¥You can get the type of a hook’s arguments by passing the hook’s name to the HookParameters
utility type. In the following example, a function’s options
argument is typed to match the parameters of the astro:config:setup
hook:
允许使用 astro add
安装
Section titled 允许使用 astro add 安装¥Allow installation with astro add
astro add
命令 允许用户轻松地将集成和适配器添加到他们的项目中。如果你希望你的集成可以使用此工具安装,请将 astro-integration
添加到 package.json
中的 keywords
字段:
¥The astro add
command allows users to easily add integrations and adapters to their project. If you want your integration to be installable with this tool, add astro-integration
to the keywords
field in your package.json
:
完成 将你的集成发布到 npm 后,运行 astro add example
将安装你的软件包以及 package.json
中指定的任何对等依赖。这也会将你的集成应用到用户的 astro.config
,如下所示:
¥Once you publish your integration to npm, running astro add example
will install your package with any peer dependencies specified in your package.json
. This will also apply your integration to the user’s astro.config
like so:
AstroIntegrationLogger
Section titled AstroIntegrationLoggerAstro 日志器的实例,可用于写入日志。该日志器使用通过 CLI 配置的相同 日志级别。
¥An instance of the Astro logger, useful to write logs. This logger uses the same log level configured via CLI.
可用于写入终端的方法:
¥Methods available to write to terminal:
-
logger.info("Message")
; -
logger.warn("Message")
; -
logger.error("Message")
; -
logger.debug("Message")
;
所有消息都前面带有一个具有相同集成值的标签。
¥All the messages are prepended with a label that has the same value of the integration.
上面的示例将记录一条消息,其中包括提供的 info
消息:
¥The example above will log a message that includes the provided info
message:
要使用不同标签记录某些消息,请使用 .fork
方法指定默认 name
的替代方法:
¥To log some messages with a different label, use the .fork
method to specify an alternative to the default name
:
上面的示例默认会生成 [astro-format]
的日志,指定时会生成 [astro-format/build]
的日志:
¥The example above will produce logs with [astro-format]
by default, and [astro-format/build]
when specified:
¥Integration Ordering
所有集成均按照配置顺序运行。例如,对于用户 astro.config.*
中的数组 [react(), svelte()]
,react
将在 svelte
之前运行。
¥All integrations are run in the order that they are configured. For instance, for the array [react(), svelte()]
in a user’s astro.config.*
, react
will run before svelte
.
理想情况下,你的集成应该以任何顺序运行。如果这不可能,我们建议记录你的集成需要位于用户的 integrations
配置数组中的第一个或最后一个。
¥Your integration should ideally run in any order. If this isn’t possible, we recommend documenting that your integration needs to come first or last in your user’s integrations
configuration array.
将集成合并到预设中
Section titled 将集成合并到预设中¥Combine integrations into presets
集成也可以编写为多个较小集成的集合。我们将这些集合称为预设。不是创建返回单个集成对象的工厂函数,而是预设返回集成对象数组。这对于从多个集成中构建复杂的功能非常有用。
¥An integration can also be written as a collection of multiple, smaller integrations. We call these collections presets. Instead of creating a factory function that returns a single integration object, a preset returns an array of integration objects. This is useful for building complex features out of multiple integrations.
¥Community Resources
-
构建你自己的 Astro 集成 - 作者:Emmanuel Ohans,来自 FreeCodeCamp
-
Astro 集成模板 - 由 Florian Lefebvre 在 GitHub 上发布