Astro 集成 API
Astro 集成只需几行代码就能为你的项目添加新的功能和行为。
这个参考页是为任何想要编写集成的人准备的。要学习如何在项目中使用集成,请查看我们的使用集成指南。
示例
当你创建自己的集成时,可以参考官方的 Astro 集成。
API 快速参考
interface AstroIntegration { name: string; hooks: { 'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build'; isRestart: boolean; updateConfig: (newConfig: Record<string, any>) => void; addRenderer: (renderer: AstroRenderer) => void; addWatchFile: (path: URL | string) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (pluginEntrypoint: string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entrypoint: string }) => void; }) => void; 'astro:config:done'?: (options: { config: AstroConfig; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:server:done'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:start'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:setup'?: (options: { vite: ViteConfigWithSSR; pages: Map<string, PageBuildData>; target: 'client' | 'server'; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifestm; entryPoints: Map<RouteData, URL>; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:done'?: (options: { dir: URL; routes: RouteData[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; };}
钩子
astro:config:setup
下一个钩子:astro:config:done
用途:扩展项目配置。包括更新 Astro 配置、应用 Vite 插件、添加组件渲染器,以及向页面注入脚本。
'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build'; isRestart: boolean; updateConfig: (newConfig: Record<string, any>) => void; addRenderer: (renderer: AstroRenderer) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (pluginEntrypoint: string) => void; addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entrypoint: string }) => void; logger: AstroIntegrationLogger;}) => void;
config
选项
类型:AstroConfig
用户提供的 Astro 配置只读副本。这是在任何其他集成运行之前进行解析的。如果在所有集成完成配置更新后需要配置副本,见astro:config:done
钩子。
command
选项
类型:'dev' / 'build'
dev
- 项目执行astro dev
或astro preview
build
- 项目执行astro build
isRestart
选项
类型:boolean
开发服务器启动时为false
,触发重载时为true
。用于检测此函数何时被多次调用。
updateConfig
选项
类型:(newConfig: Record<string, any>) => void;
用来更新用户提供的Astro 配置的回调函数。你提供的任何配置将与用户配置 + 其他集成配置的更新合并,所以你可以随意省略键名!
例如,假设你需要在项目使用 Vite 插件:
import bananaCSS from '@vitejs/official-banana-css-plugin';
export default { name: 'banana-css-integration', hooks: { 'astro:config:setup': ({ updateConfig }) => { updateConfig({ vite: { plugins: [bananaCSS()], } }) } }}
addRenderer
选项
类型:(renderer:
AstroRenderer
) => void;
示例:lit
、svelte
、react
、preact
、vue
、solid
用于添加组件框架渲染器(即 React、Vue、Svelte 等)的回调函数。你可以浏览上面的例子和类型定义,了解更多的高级选项,但需要注意两个注意选项:
clientEntrypoint
- 当组件被使用时,在客户端执行的文件的路径。这主要是为了使用 JS 渲染或填充你的组件。serverEntrypoint
- 文件路径,在服务器端请求或静态构建时,只要使用组件就会执行。这些文件应该将组件渲染成静态标记,并在适当的时候使用钩子进行激活。React 的renderToString
回调函数是个典型例子。
addWatchFile
选项
类型: URL | string
如果你的集成依赖于一些 Vite 不监听或者需要完整的开发服务器重启才能生效的配置文件,请用addWatchFile
添加它。每当该文件发生变化,Astro 开发服务器将重新加载(你可以用isRestart
检查何时发生重新加载)。
使用示例:
// 必须是绝对路径!addWatchFile('/home/user/.../my-config.json');addWatchFile(new URL('./tailwind.config.js', config.root));
addClientDirective
选项
添加于:
astro@2.6.0
类型: (directive:
ClientDirectiveConfig
) => void;
添加一个 自定义客户端指令,用于在 .astro
文件中使用。
请注意,指令入口点仅通过 esbuild 进行打包,并且应保持较小,以避免减慢组件注水的速度。
示例用法:
import { defineConfig } from 'astro/config';import clickDirective from './astro-click-directive/register.js'
// https://astro.build/configexport default defineConfig({ integrations: [ clickDirective() ],});
/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "client:click", hooks: { "astro:config:setup": ({ addClientDirective }) => { addClientDirective({ name: "click", entrypoint: "./astro-click-directive/click.js", }); }, },});
/** * Hydrate on first click on the window * @type {import('astro').ClientDirective} */export default (load, opts, el) => { window.addEventListener('click', async () => { const hydrate = await load() await hydrate() }, { once: true })}
你还可以在库的类型定义文件中为指令添加类型:
import 'astro'declare module 'astro' { interface AstroClientDirectives { 'client:click'?: boolean }}
addDevToolbarApp
选项
添加于:
astro@4.0
新
类型: (pluginEntrypoint: string) => void;
添加一个自定义的开发工具栏应用 (EN)。
使用示例:
import { defineConfig } from 'astro/config';import devToolbarIntegration from './astro-dev-toolbar-app/integration.js'
// https://astro.build/configexport default defineConfig({ integrations: [ devToolbarIntegration() ],});
/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "dev-toolbar-app", hooks: { "astro:config:setup": ({ addDevToolbarApp }) => { addDevToolbarApp("./astro-dev-toolbar-app/plugin.js"); }, },});
/** * @type {import('astro').DevToolbarApp} */export default { id: "my-app", name: "My App", icon: "<svg>...</svg>", init() { console.log("I'm a dev toolbar app!") },};
addMiddleware
选项
添加于:
astro@3.5.0
类型: (middleware:
AstroIntegrationMiddleware
) => void;
添加中间件以在每个请求上运行。接受包含中间件的 entrypoint
模块,以及一个 order
参数来指定它应该在其他中间件之前(pre
)运行还是之后(post
)运行。
/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-middleware-package", hooks: { "astro:config:setup": ({ addMiddleware }) => { addMiddleware({ entrypoint: '@my-package/middleware', order: 'pre' }); }, },});
中间件在一个包中定义,它有一个对应的 onRequest
函数,就像用户定义的中间件一样。
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, request) => { if(context.url.pathname === '/some-test-path') { return Response.json({ ok: true }); }});
injectRoute
选项
类型:({ pattern: string, entrypoint: string }) => void;
用于向 Astro 项目注入路由的回调函数。注入的路由可以是 .astro
页面 或 .js
和.ts
路由处理程序。
injectRoute
接收带有 pattern
和 entrypoint
的对象值。
pattern
- 应该在浏览器中使用的路由,例如/foo/bar
。pattern
可以使用 Astro 的文件路径语法来表示动态路由,例如/foo/[bar]
或/foo/[...bar]
。请注意,在pattern
中无需文件扩展名。entrypoint
— 裸模块指定器,指向.astro
页面或.js
/.ts
路由处理程序,处理pattern
中指定路由。
使用示例
injectRoute({ // 使用 Astro 语法模式来匹配动态路由 pattern: '/subfolder/[dynamic]', // 使用相对路径语法来匹配本地路由 entrypoint: './src/dynamic-page.astro'});
对于设计用于安装在其他项目中的集成,使用其包名来引用路由的入口点。
下面的示例展示了一个以 @fancy/dashboard
发布到 npm 上的包,在路由中注入一个仪表盘:
injectRoute({ pattern: '/fancy-dashboard', entrypoint: '@fancy/dashboard/dashboard.astro'});
injectScript
选项
类型:(stage: InjectedScriptStage, content: string) => void;
回调函数,在每个页面上注入 JavaScript 内容。
stage
表示这个脚本(content
)应该如何插入。有些阶段允许不加修改地插入脚本,而有些阶段允许在 Vite 的捆绑步骤中进行压缩:
-
head-inline
:注入每个页面的<head>
中的脚本标签。不由 Vite 压缩或解析。 -
before-hydration
:在激活脚本运行之前导入客户端。由 Vite 优化和解决。 -
page
:与head-inline
类似,只是注入片段由 Vite 进行处理,并与页面上 Astro 组件内定义的其他<script>
标签捆绑在一起。该脚本将在最终的页面输出中以<script type="module">
的形式加载,并由 Vite 压缩和解析。 -
page-ssr
:在每个 Astro 页面组件的 frontmatter 中作为单独的模块被导入。因为这个阶段导入你的脚本,无法使用全局Astro
,脚本只会在import
第一次 evaluate 时运行一次。page-ssr
阶段的主要是将 CSSimport
注入到每个页面,并由 Vite 进行优化和解析。injectScript('page-ssr', 'import "global-styles.css";');
astro:config:done
上一个钩子:astro:config:setup
下一个钩子:当在开发模式下运行时为 astro:server:setup
,在生产构建时为 astro:build
时机:在 Astro 配置解析后,其他集成已经运行 astro:config:setup
钩子后。
原因:检索最终的配置,以便在其他钩子中使用。
'astro:config:done'?: (options: { config: AstroConfig }) => void | Promise<void>;
config
选项
类型:AstroConfig
用户提供的 Astro 配置的只读副本。这在其他集成运行后进行解析。
astro:server:setup
上一个钩子:astro:config:done
下一个钩子:astro:server:start
时机:在开发模式下创建 Vite 服务器后,但在 listen()
事件触发前。详见Vite 的 createServer API。
用途:更新 Vite 服务端选项和中间件。
'astro:server:setup'?: (options: { server: vite.ViteDevServer }) => void | Promise<void>;
server
选项
在开发模式下使用的 Vite 服务器的可变实例。例如,在 Partytown 集成中使用,以注入 Partytown 服务器作为中间件。
export default { name: 'partytown', hooks: { 'astro:server:setup': ({ server }) => { server.middlewares.use( function middleware(req, res, next) { // handle requests } ); } }}
astro:server:start
上一个钩子:astro:server:setup
下一个钩子:astro:server:done
时机:在服务端 listen()
事件触发之后。
用途:拦截指定地址的网络请求。如果你打算将这个地址用于中间件,请考虑使用 astro:server:setup
来代替。
'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>;
address
选项
类型:AddressInfo
由 NodeJS Net 模块提供的地址、协议族名和端口。
astro:server:done
上一个钩子:astro:server:start
时机:在开发服务器关闭后。
用途:在运行 astro:server:setup
或 astro:server:start
钩子中可能触发的清理事件。
'astro:server:done'?: () => void | Promise<void>;
astro:build:start
上一个钩子:astro:config:done
下一个钩子:astro:build:setup
时机:在 astro:config:done
事件之后,但在生产构建开始前。
用途:设置生产构建过程中需要的任何全局对象或客户端。这也可以扩展适配器 API中的构建配置选项。
'astro:build:start'?: () => void | Promise<void>;
astro:build:setup
上一个钩子:astro:build:start
下一个钩子:astro:build:ssr
何时:在 astro:build:start
钩子后,在构建之前立即运行。
用途:此时,用于构建的 Vite 配置已经完全建成,这是你修改它的最后机会。例如,这可以用来覆盖一些默认值。如果你不确定你应该使用这个钩子还是 astro:build:start
,请使用 astro:build:start
。
'astro:build:setup'?: (options: { vite: ViteConfigWithSSR; pages: Map<string, PageBuildData>; target: 'client' | 'server';}) => void | Promise<void>;
astro:build:generated
上一个钩子: astro:build:setup
何时:在静态生产构建完成生成路由和资源之后。
用途:在清理构建产物之前访问生成的路由和资源。这是一个非常不常见的用例。我们建议使用astro:build:done
,除非你真的需要在清理前访问生成的文件。
'astro:build:generated'?: (options: { dir: URL }) => void | Promise<void>;
astro:build:ssr
上一个钩子:astro:build:setup
时机:在生产 SSR 构建完成之后。
原因:获取 SSR manifest,这在插件或集成中创建自定义 SSR 构建时很有用。
entryPoints
将页面路由映射到构建后的物理文件;middlewareEntryPoint
是中间件文件的文件系统路径。
'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest, entryPoints: Map<RouteData, URL>, middlewareEntryPoint: URL}) => void | Promise<void>;
astro:build:done
上一个钩子:astro:build:ssr
何时:在生产构建(SSG 或 SSR)完成后。
用途:访问生成的路由和资产进行扩展(例如,将内容复制到生成的 /assets
目录)。如果你打算转换生成的资源,我们建议探索 Vite 插件 API 和通过 astro:config:setup
进行配置来代替。
'astro:build:done'?: (options: { dir: URL; routes: RouteData[] }) => void | Promise<void>;
dir
option
类型:URL
指向构建输出目录的链接。注意,如果你需要有效的绝对路径字符串,你应该使用 Node 内置的 fileURLToPath
工具。
import { writeFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';
export default function myIntegration() { return { hooks: { 'astro:build:done': async ({ dir }) => { const metadata = await getIntegrationMetadata(); // 使用 fileURLToPath 获得有效、跨平台绝对路径字符串 const outFile = fileURLToPath(new URL('./my-integration.json', dir)); await writeFile(outFile, JSON.stringify(metadata)); } } }}
routes
option
类型:RouteData[]
所有生成的路由及其相关元数据的列表。
你可以参考下面完整的 RouteData
类型,但最常见的属性是。
component
- 相对于项目根的输入文件路径pathname
- 输出文件的 URL(对于使用[dynamic]
和[...spread]
参数的路由未定义)。
RouteData
类型参考
interface RouteData { /** 指定路由是 HTML 页面还是非 HTML 端点 */ type: 'page' | 'endpoint'; /** 组件源码链接 */ component: string; /** * 将使用的输出链接路径名 * 注意:[dynamic] 和 [...spread] 路由将为 undefined */ pathname?: string; /** * 用于匹配输入链接和请求的路由的正则表达式 * 如 `[fruit]/about.astro` 将生成 /^\/([^/]+?)\/about\/?$/ 匹配模式 * pattern.test("banana/about") 为 `true` */ pattern: RegExp; /** * 动态和扩展路由参数 * 如 `/pages/[lang]/[..slug].astro` 将输出参数 ['lang', '...slug'] */ params: string[]; /** * 类似于 `params` 字段,但有更多相关的元数据 * 如 `/pages/[lang]/index.astro` 将输出分段 * [[ { content: 'lang', dynamic: true, spread: false } ]] */ segments: { content: string; dynamic: boolean; spread: boolean; }[][]; /** * 根据输入数据中就地渲染组件的函数。 * 这通常仅在内部使用,所以请谨慎调用! */ generate: (data?: any) => string;}
pages
选项
类型: { pathname: string }[]
生成的所有页面的列表是一个包含一个属性的对象。
pathname
- 页面的最终路径。
使用 astro add
安装
用户可以使用 astro add
命令 轻松地在他们的项目中添加集成和适配器。如果你想让别人可以使用这个工具安装你的集成,在你的 package.json
中的 keywords
字段中添加 astro-integration
:
{ "name": "example", "keywords": ["astro-integration"],}
在你将集成发布到 npm后,即可运行 astro add example
安装包和 package.json
中指定的对等依赖。同时也会将你的集成应用到用户的 astro.config
中,就像这样:
import { defineConfig } from 'astro/config'; import example from 'example';
export default defineConfig({ integrations: [example()],})
这假定你的集成定义是:1)default
导出;2)函数。在添加 astro-integration
关键字前,请确保符合要求。
AstroIntegrationLogger
Astro 日志记录器的实例,用于写日志。此日志记录器使用与 CLI 配置的相同的日志级别。
用于写入终端的可用方法:
logger.info("Message")
;logger.warn("Message")
;logger.error("Message")
;logger.debug("Message")
;
所有消息都前面带有一个具有集成名字的标签。
import type { AstroIntegration } from "astro";export function formatIntegration(): AstroIntegration { return { name: "astro-format", hooks: { "astro:build:done": ({ logger }) => { // do something logger.info("Integration ready."); } } }}
上面的示例将记录一个包含提供的 info
消息的日志:
[astro-format] Integration ready.
要使用不同的标签记录一些日志,请使用 .fork
方法指定一个新的 name
:
import type { AstroIntegration } from "astro";export function formatIntegration(): AstroIntegration { return { name: "astro-format", hooks: { "astro:config:done": ({ logger }) => { // do something logger.info("Integration ready."); }, "astro:build:done": ({ logger }) => { const buildLogger = logger.fork("astro-format/build"); // do something buildLogger.info("Build finished.") } } }}
上面的示例将默认生成带有 [astro-format]
的日志,并在指定名字时生成带有 [astro-format/build]
的日志:
[astro-format] Integration ready.[astro-format/build] Build finished.
集成排序
所有的集成都是按照配置的顺序运行的。例如,在 astro.config.*
中的数组 [react(), svelte()]
,react
将在 svelte
之前运行。
你的集成最好能以任何顺序运行。如果不行我们建议在文档中注明你的集成需要排在 integrations
配置数组的第一位或最后一位。
合并预置集成
一个集成也可以写成多个较小集成的集合。我们称这些集合为预设。预设不是创建返回单个集成对象的工厂函数,而是返回集成对象的数组。这对于从多个集成中构建复杂的功能非常有用。
integrations: [ // 示例:examplePreset() 将返回 [integrationOne, integrationTwo, ...etc] examplePreset()]
社区资源
构建你自己的 Astro 集成 - 由 FreeCodeCamp 的 Emmanuel Ohans 撰写
Reference