Astro 集成 API
Astro 集成只需几行代码就能为你的项目添加新的功能和行为。
这个参考页是为任何想要编写集成的人准备的。要学习如何在项目中使用集成,请查看我们的使用集成指南。
当你创建自己的集成时,可以参考官方的 Astro 集成。
API 快速参考
Section titled “API 快速参考”interface AstroIntegration { name: string; hooks: { 'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build' | 'preview' | 'sync'; isRestart: boolean; updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; addRenderer: (renderer: AstroRenderer) => void; addWatchFile: (path: URL | string) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: (injectedRoute: InjectedRoute) => void; createCodegenDir: () => URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:route:setup'?: (options: { route: RouteOptions; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:routes:resolved'?: (options: { routes: IntegrationResolvedRoute[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:config:done'?: (options: { config: AstroConfig; setAdapter: (adapter: AstroAdapter) => void; injectTypes: (injectedType: InjectedType) => URL; logger: AstroIntegrationLogger; buildOutput: 'static' | 'server'; }) => void | Promise<void>; 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; refreshContent?: (options: RefreshContentOptions) => Promise<void>; }) => 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: vite.InlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: vite.InlineConfig) => void; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; entryPoints: Map<IntegrationRouteData, URL>; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; assets: Map<string, URL[]>; logger: AstroIntegrationLogger; }) => void | Promise<void>;
// ...任何来自集成的自定义钩子 };}Astro 提供了集成可以实现的钩子,以便在 Astro 生命周期的某些部分执行。Astro 钩子被定义在 IntegrationHooks 接口中,该接口是全局 Astro 命名空间的一部分。每个钩子都有一个 logger 选项,用于允许你使用 Astro 记录器来记录日志。
Astro 内置了以下钩子:
astro:config:setup
Section titled “astro:config:setup”下一个钩子: astro:route:setup
时机: 初始化时,在 Vite 或Astro 配置 解析前。
用途: 扩展项目配置。包括更新 Astro 配置、应用 Vite 插件、添加组件渲染器,以及向页面注入脚本。
'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build' | 'preview' | 'sync'; isRestart: boolean; updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; addRenderer: (renderer: AstroRenderer) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void; addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: (injectedRoute: InjectedRoute) => void; createCodegenDir: () => URL; logger: AstroIntegrationLogger;}) => void | Promise<void>;config 选项
Section titled “config 选项”类型: AstroConfig
用户提供的 Astro 配置只读副本。这是在任何其他集成运行之前进行解析的。如果在所有集成完成配置更新后需要配置副本,见astro:config:done 钩子。
command 选项
Section titled “command 选项”类型: 'dev' | 'build' | 'preview' | 'sync'
dev- 项目执行astro devbuild- 项目执行astro buildpreview- 项目执行astro previewsync- 项目执行astro sync
isRestart 选项
Section titled “isRestart 选项”类型: boolean
astro@1.5.0
开发服务器启动时为false,触发重载时为true。用于检测此函数何时被多次调用。
updateConfig() 选项
Section titled “updateConfig() 选项”类型: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
用来更新用户提供的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() 选项
Section titled “addRenderer() 选项”类型: (renderer: AstroRenderer) => void;
示例: svelte、react、preact、vue、solid
用于添加组件框架渲染器(即 React、Vue、Svelte 等)的回调函数。你可以浏览上面的例子和类型定义,了解更多的高级选项,但需要注意两个注意选项:
clientEntrypoint- 当组件被使用时,在客户端执行的文件的路径。这主要是为了使用 JS 渲染或填充你的组件。serverEntrypoint- 文件路径,在服务器端请求或静态构建时,只要使用组件就会执行。这些文件应该将组件渲染成静态标记,并在适当的时候使用钩子进行激活。React 的renderToString回调函数是个典型例子。
添加于:
astro@5.0.0
函数 clientEntrypoint 和 serverEntrypoint 接收一个 URL。
addWatchFile() 选项
Section titled “addWatchFile() 选项”类型: (path: URL | string) => void
astro@1.5.0
如果你的集成依赖于一些 Vite 不监听或者需要完整的开发服务器重启才能生效的配置文件,请用addWatchFile() 添加它。每当该文件发生变化,Astro 开发服务器将重新加载(你可以用 isRestart 检查何时发生重新加载)。
使用示例:
// 必须是绝对路径!addWatchFile('/home/user/.../my-config.json');addWatchFile(new URL('./ec.config.mjs', config.root));addClientDirective() 选项
Section titled “addClientDirective() 选项”类型: (directive: ClientDirectiveConfig) => void;
astro@2.6.0
添加一个 自定义客户端指令,用于在 .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", }); }, },});/** * 第一次触发 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() 选项
Section titled “addDevToolbarApp() 选项”类型: (entrypoint: DevToolbarAppEntry) => void;
astro@3.4.0
添加一个自定义的开发工具栏应用。
使用示例:
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({ entrypoint: "./astro-dev-toolbar-app/plugin.js", id: "my-plugin", name: "My Plugin" }); }, },});/** * @type {import('astro').DevToolbarApp} */export default { id: "my-plugin", name: "My Plugin", icon: "<svg>...</svg>", init() { console.log("I'm a dev toolbar app!") },};addMiddleware() 选项
Section titled “addMiddleware() 选项”类型: (middleware: AstroIntegrationMiddleware) => void;
astro@3.5.0
添加中间件以在每个请求上运行。接受包含中间件的 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, next) => { if(context.url.pathname === '/some-test-path') { return Response.json({ ok: true }); }
return next();});
添加于:
astro@5.0.0
该函数也接受 URL 作为 entrypoint:
/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-middleware-package", hooks: { "astro:config:setup": ({ addMiddleware }) => { addMiddleware({ entrypoint: new URL('./middleware.js', import.meta.url), order: 'pre' }); }, },});injectRoute() 选项
Section titled “injectRoute() 选项”类型: ({ pattern: string; entrypoint: string | URL; prerender?: boolean }) => void;
用于向 Astro 项目注入路由的回调函数。注入的路由可以是 .astro页面 或 .js和.ts路由处理程序。
injectRoute() 接收带有 pattern 和 entrypoint 的对象值。
pattern- 应该在浏览器中使用的路由,例如/foo/bar。pattern可以使用 Astro 的文件路径语法来表示动态路由,例如/foo/[bar]或/foo/[...bar]。请注意,在pattern中无需文件扩展名。entrypoint— 裸模块指定器,指向.astro页面或.js/.ts路由处理程序,处理pattern中指定路由。prerender- 如果 Astro 无法检测到你的prerender导出,则设置一个布尔值。
injectRoute({ // 使用 Astro 语法模式来匹配动态路由 pattern: '/subfolder/[dynamic]', // 使用相对路径语法来匹配本地路由 entrypoint: './src/dynamic-page.astro', // 仅当 Astro 无法检测到你的预渲染导出时才使用 prerender: false});对于设计用于安装在其他项目中的集成,使用其包名来引用路由的入口点。下面的示例展示了一个以 @fancy/dashboard 发布到 npm 上的包,在路由中注入一个仪表盘:
injectRoute({ pattern: '/fancy-dashboard', entrypoint: '@fancy/dashboard/dashboard.astro'});当你将你的包(在这个例子中是 @fancy/dashboard)发布到 npm 上时,你必须在你的 package.json 中导出 dashboard.astro:
{ "name": "@fancy/dashboard", // ... "exports": { "./dashboard.astro": "./dashboard.astro" }}
添加于:
astro@5.0.0
该函数也接受 URL 作为 entrypoint:
injectRoute({ pattern: '/fancy-dashboard', entrypoint: new URL('./dashboard.astro', import.meta.url)});injectScript() 选项
Section titled “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";');
createCodegenDir()
Section titled “createCodegenDir()”类型: () => URL;
astro@5.0.0
一个函数,用于创建 <root>/.astro/integrations/<normalized_integration_name> 文件夹并返回其路径。
它允许你拥有一个专用文件夹,避免与其他集成或 Astro 本身发生冲突。该目录是通过调用此函数创建的,因此可以安全地直接向其中写入文件:
import { writeFileSync } from 'node:fs'
const integration = { name: 'my-integration', hooks: { 'astro:config:setup': ({ createCodegenDir }) => { const codegenDir = createCodegenDir() writeFileSync(new URL('cache.json', codegenDir), '{}', 'utf-8') } }}astro:route:setup
Section titled “astro:route:setup”
添加于:
astro@4.14.0
上一个钩子: astro:config:setup
下一个钩子: astro:routes:resolved
时机: 在 astro bulid 中,在构建开始前。在 astro dev 中,当绘制模块依赖关系图以及对基于文件的路由发生更改(添加/移除/更新)时。
用途: 在构建或请求时为路由设置选项,例如启用 按需服务器渲染。
'astro:route:setup'?: (options: { route: RouteOptions; logger: AstroIntegrationLogger;}) => void | Promise<void>;route 选项
Section titled “route 选项”类型: { readonly component: string; prerender?: boolean; }
具有 component 属性的对象用于标识路由,以及以下附加值,以允许你配置生成的路由:prerender。
route.component
Section titled “route.component”类型: string
astro@4.14.0
component 属性指示了将在路由上进行渲染的入口点。你通过在路由构建之前,通过配置该页面的服务器端的按需渲染,来访问此值。
route.prerender
Section titled “route.prerender”类型: boolean
默认值: undefined
astro@4.14.0
prerender 属性用于配置按需服务器渲染的路由。如果路由文件包含一个显式的 export const prerender 值,该值将被用作默认值,而不是 undefined。
import { defineConfig } from 'astro/config';
export default defineConfig({ integrations: [setPrerender()],});
function setPrerender() { return { name: 'set-prerender', hooks: { 'astro:route:setup': ({ route }) => { if (route.component.endsWith('/blog/[slug].astro')) { route.prerender = true; } }, }, };}如果在运行所有钩子后的最终值是 undefined,路由将根据 output 选项 回退到预渲染的默认值:static 模式下预渲染,server 模式下按需渲染。
astro:routes:resolved
Section titled “astro:routes:resolved”
添加于:
astro@5.0.0
上一个钩子: astro:route:setup
下一个钩子: astro:config:done(仅在 setup 期间)
时机: 在 astro dev 中,如果基于文件的路由发生更改(添加/删除/更新),它也会运行。
用途: 为了读取路径及其元数据。
'astro:routes:resolved'?: (options: { routes: IntegrationResolvedRoute[]; logger: AstroIntegrationLogger;}) => void | Promise<void>;routes 选项
Section titled “routes 选项”类型: IntegrationResolvedRoute[]
一个包含了所有路由及其关联元数据的列表。
使用示例:
const integration = () => { return { name: 'my-integration', hooks: { 'astro:routes:resolved': ({ routes }) => { const projectRoutes = routes.filter(r => r.origin === 'project').map(r => r.pattern)
console.log(projectRoutes) }, } }}astro:config:done
Section titled “astro:config:done”上一个钩子: astro:routes:resolved
下一个钩子: 当在开发模式下运行时为 astro:server:setup,在生产构建时为 astro:build:start
时机: 在 Astro 配置解析后,其他集成已经运行 astro:config:setup 钩子后。
用途: 检索最终的配置,以便在其他钩子中使用。
'astro:config:done'?: (options: { config: AstroConfig; setAdapter: (adapter: AstroAdapter) => void; injectTypes: (injectedType: InjectedType) => URL; logger: AstroIntegrationLogger; buildOutput: 'static' | 'server';}) => void | Promise<void>;config 选项
Section titled “config 选项”类型: AstroConfig
用户提供的 Astro 配置 的只读副本。这在其他集成 运行后 进行解析。
setAdapter() 选项
Section titled “setAdapter() 选项”类型: (adapter: AstroAdapter) => void;
使集成成为适配器。在 适配器 API 中阅读更多内容。
injectTypes() 选项
Section titled “injectTypes() 选项”类型: (injectedType: { filename: string; content: string }) => URL
astro@4.14.0
允许你通过添加一个新的 *.d.ts 文件将类型注入到用户的项目中。
filename 属性将用于在 /.astro/integrations/<normalized_integration_name>/<normalized_filename>.d.ts 生成文件,必须以 ".d.ts" 结尾。
content 属性将用于在文件中生成内容,必须是有效的 TypeScript。
此外,injectTypes() 返回一个 URL,指向规范化路径,以便稍后覆盖其内容,或以任何你想要的方式操作它。
const path = injectTypes({ filename: "types.d.ts", content: "declare module 'virtual:integration' {}"})console.log(path) // URLbuildOutput 选项
Section titled “buildOutput 选项”类型: 'static' | 'server'
astro@5.0.0
允许你可以根据用户的项目输出来调整集成的逻辑。
astro:server:setup
Section titled “astro:server:setup”上一个钩子: astro:config:done
下一个钩子: astro:server:start
时机: 在开发模式下创建 Vite 服务器后,但在 listen() 事件触发前。详见 Vite 的 createServer API。
用途: 更新 Vite 服务端选项和中间件,或通过刷新以实现对 content layer 的支持。
'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; refreshContent: (options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>;}) => void | Promise<void>;server 选项
Section titled “server 选项”在开发模式下使用的 Vite 服务器的可变实例。例如,在 Partytown 集成中使用,以注入 Partytown 服务器作为中间件。
export default { name: 'partytown', hooks: { 'astro:server:setup': ({ server }) => { server.middlewares.use( function middleware(req, res, next) { // 处理请求 } ); } }}toolbar 选项
Section titled “toolbar 选项”类型: ReturnType<typeof getToolbarServerCommunicationHelpers>
astro@4.7.0
一个对象,用于提供回调函数与 开发工具栏 进行交互:
toolbar.on()
Section titled “toolbar.on()”类型: <T>(event: string, callback: (data: T) => void) => void
一个函数,接收一个事件名称作为第一个参数,接收一个回调函数作为第二个参数。该函数允许你可以从开发工具栏应用接收一条消息,其中包含与该事件相关的数据。
toolbar.nAppInitialized()
Section titled “toolbar.nAppInitialized()”类型: (appId: string, callback: (data: Record<string, never>) => void) => void
一个函数,当开发工具栏应用初始化时触发。第一个参数是初始化应用的 ID。第二个参数是在初始化应用时运行的回调函数。
toolbar.onAppToggled()
Section titled “toolbar.onAppToggled()”类型: (appId: string, callback: (data: { state: boolean; }) => void) => void
一个函数,当开发工具栏应用切换为开启或关闭状态时触发。第一个参数是切换应用的 ID。第二个参数是一个回调函数,该函数在应用状态发生切换时提供了要执行的状态。
toolbar.send()
Section titled “toolbar.send()”类型: <T>(event: string, payload: T) => void
一个函数,用于向开发工具栏发送应用程序可以接收到的信息。该函数接受一个事件名称作为第一个参数,接受一个有效载荷作为第二个参数,可以是任何可序列化的数据。
refreshContent 选项
Section titled “refreshContent 选项”类型: (options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>
astro@5.0.0
一个用于在 astro dev 时触发,以更新 content layer 的函数。可以这样使用,例如,要在开发时注册一个 webhook 端点,或者开启一个 socket 来监听 CMS 的改动。
默认情况下,refreshContent() 会刷新所有的集合。你可以选择性的提供一个 loaders 属性去传递,即一个包含着加载器(loader)名称的数组。如果提供的话,那么就只有使用了这些加载器的集合会被刷新。例如,一个 CMS 集成可以使用该属性来单独刷新它自己的集合。
你也可以传递一个 context 对象给加载器。它可以用来传递任意数据,例如 webhook body,或者是来自 websocket 的事件。
{ name: 'my-integration', hooks: { 'astro:server:setup': async ({ server, refreshContent }) => { // 注册一个开发服务器的 webhook 端点 server.middlewares.use('/_refresh', async (req, res) => { if(req.method !== 'POST') { res.statusCode = 405 res.end('Method Not Allowed'); return } let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', async () => { try { const webhookBody = JSON.parse(body); await refreshContent({ context: { webhookBody }, loaders: ['my-loader'] }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Content refreshed successfully' })); } catch (error) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Failed to refresh content: ' + error.message })); } }); }); } }}加载器稍后可以通过读取 refreshContextData 属性来获得 webhook body。更多信息请参阅 refreshContextData 属性。
astro:server:start
Section titled “astro:server:start”上一个钩子: astro:server:setup
下一个钩子: astro:server:done
时机: 在服务端 listen() 事件触发之后。
用途: 拦截指定地址的网络请求。如果你打算将这个地址用于中间件,请考虑使用 astro:server:setup 来代替。
'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger;}) => void | Promise<void>;address 选项
Section titled “address 选项”类型: AddressInfo
由 Node.js Net 模块的 server.address() 方法 提供的地址、协议族名和端口。
astro:server:done
Section titled “astro:server:done”上一个钩子: astro:server:start
时机: 在开发服务器关闭后。
用途: 在运行 astro:server:setup 或 astro:server:start 钩子中可能触发的清理事件。
'astro:server:done'?: (options: { logger: AstroIntegrationLogger;}) => void | Promise<void>;astro:build:start
Section titled “astro:build:start”上一个钩子: astro:config:done
下一个钩子: astro:build:setup
时机: 在 astro:config:done 事件之后,但在生产构建开始前。
用途: 设置生产构建过程中需要的任何全局对象或客户端。这也可以扩展 适配器 API 中的构建配置选项。
'astro:build:start'?: (options: { logger: AstroIntegrationLogger;}) => void | Promise<void>;astro:build:setup
Section titled “astro:build:setup”上一个钩子: astro:build:start
下一个钩子: astro:build:ssr
时机: 在 astro:build:start 钩子后,在构建之前立即运行。
用途: 此时,用于构建的 Vite 配置已经完全建成,这是你修改它的最后机会。例如,这可以用来覆盖一些默认值。如果你不确定你应该使用这个钩子还是 astro:build:start,请使用 astro:build:start。
'astro:build:setup'?: (options: { vite: vite.InlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: vite.InlineConfig) => void; logger: AstroIntegrationLogger;}) => void | Promise<void>;vite 选项
Section titled “vite 选项”类型: InlineConfig
一个对象,允许你访问构建中使用的 Vite 配置。
如果你需要访问集成中的配置选项,这可能很有用:
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ vite }) => { const { publicDir, root } = vite; }, }}pages 选项
Section titled “pages 选项”类型: Map<string, PageBuildData>
一个 Map 对象,其中将页面列表作为键,将其构建的数据作为值。
可用于在路由和一种准则匹配时,执行一些行为:
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ pages }) => { pages.forEach((data) => { if (data.route.pattern.test("/blog")) { console.log(data.route.type); } }); }, }}PageBuildData 对象
Section titled “PageBuildData 对象”描述如何构建页面。
PageBuildData.key
Section titled “PageBuildData.key”类型: string
astro@4.8.0
指定页面的唯一标识符。
PageBuildData.component
Section titled “PageBuildData.component”类型: string
指定源组件的URL。
PageBuildData.route
Section titled “PageBuildData.route”类型: RouteData
描述关于页面路由的信息。
PageBuildData.moduleSpecifier
Section titled “PageBuildData.moduleSpecifier”类型: string
定义一个可以解析为模块文件路径的字符串。
PageBuildData.styles
Section titled “PageBuildData.styles”类型: Array<{ depth: number; order: number; sheet: { type: 'inline'; content: string } | { type: 'external'; src: string } }>
astro@2.4.0
在页面上渲染的样式列表。每个样式包含其在组件树中的 depth 以及在页面上的显示 order,并指明该样式应作为内联还是外部样式应用。
target 选项
Section titled “target 选项”类型: 'client' | 'server'
构建分为两个不同的阶段: client 和 server。该选项允许由你来确定当前的构建阶段。
只能用于在特定阶段执行一些行为:
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ target }) => { if (target === "server") { // 在服务器构建阶段执行一些行为 } }, }}updateConfig() 选项
Section titled “updateConfig() 选项”类型: (newConfig: InlineConfig) => void
一个回调函数,用于在构建阶段更新 Vite 选项。你提供的任何配置都将与 用户配置 + 其他集成配置更新合并,因此你可以自由地省略键!
例如,该选项可用于为用户的项目提供插件:
import awesomeCssPlugin from 'awesome-css-vite-plugin';
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ updateConfig }) => { updateConfig({ plugins: [awesomeCssPlugin()], }) } }}astro:build:ssr
Section titled “astro:build:ssr”上一个钩子: astro:build:setup
下一个钩子: astro:build:generated
时机: 在生产 SSR 构建完成之后。
用途: 获取 SSR 清单(manifest),这在插件或集成中创建自定义 SSR 构建时很有用。
entryPoints将页面路由映射到构建后的物理文件;middlewareEntryPoint是中间件文件的文件系统路径。
'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; entryPoints: Map<IntegrationRouteData, URL>; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger;}) => void | Promise<void>;manifest 选项
Section titled “manifest 选项”类型: SerializedSSRManifest
允许你通过访问 SSRManifest 的序列化版本来创建自定义构建。这包含与 SSRManifest 相同的信息,其中某些属性已转换为可序列化格式。
下面的示例会检查存储在 manifest 中的 i18n.strategy 配置:
export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ manifest }) => { const { i18n } = manifest; if (i18n?.strategy === "domains-prefix-always") { // 执行一些行为 } }, },}manifest.routes
Section titled “manifest.routes”类型: SerializedRouteInfo[]
定义了一个序列化路由信息的列表。每个路由包含与 SSRManifest.routes 相同的属性,其中 routeData 被转换为 JSON 可序列化格式。
manifest.assets
Section titled “manifest.assets”类型: string[]
定义序列化资源文件路径的列表。
manifest.componentMetadata
Section titled “manifest.componentMetadata”类型: [string, SSRComponentMetadata][]
astro@2.1.7
定义一个键值对数组,其中第一个元素是组件标识符,第二个元素是描述构建元数据的对象。
manifest.inlinedScripts
Section titled “manifest.inlinedScripts”类型: [string, string][]
定义一组键值对数组,其中每一项都是一个元组。第一个元素是脚本标识符,第二个是脚本内容。
manifest.clientDirectives
Section titled “manifest.clientDirectives”类型: [string, string][]
astro@2.5.0
定义一个键值对数组,其中第一个元素是指令名称(例如 load、visible),第二个是该指令的实现代码。
manifest.serverIslandNameMap
Section titled “manifest.serverIslandNameMap”类型: [string, string][]
astro@4.12.0
定义一个键值对数组,其中每个条目都是一个元组。第一个元素是组件路径,第二个是分配的名称。
manifest.key
Section titled “manifest.key”类型: string
astro@4.13.4
指定用于加密服务器岛屿属性的加密密钥,以字符串形式序列化。
entryPoints 选项
Section titled “entryPoints 选项”类型: Map<IntegrationRouteData, URL>
astro@2.7.0
一个包含了 ssr 所发出的入口点的 Map 对象,其中 IntegrationRouteData 作为键,物理文件 URL 作为值。
export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ entryPoints }) => { entryPoints.forEach((url) => { console.log(url.href); }); }, },}middlewareEntryPoint 选项
Section titled “middlewareEntryPoint 选项”类型: URL | undefined
astro@2.8.0
暴露出 中间件 的文件路径。
export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ middlewareEntryPoint }) => { if (middlewareEntryPoint) { // 如果中间件存在,可执行一些行为 } }, },}astro:build:generated
Section titled “astro:build:generated”
添加于:
astro@1.3.0
上一个钩子: astro:build:ssr
下一个钩子: astro:build:done
时机: 在静态生产构建完成生成路由和资源之后。
用途: 在清理构建产物 之前 访问生成的路由和资源。这是一个非常少见的用例。我们建议使用 astro:build:done,除非你真的需要在清理前访问生成的文件。
'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger;}) => void | Promise<void>;dir 选项
Section titled “dir 选项”类型: URL
一个构建输出目录的 URL 路径。
下面的示例使用 Node 内置的 fileURLToPath 工具函数来计算由集成提供的文件的有效绝对路径字符串:
import { fileURLToPath } from 'node:url';
export default { name: 'my-integration', hooks: { 'astro:build:generated': ({ dir }) => { const outFile = fileURLToPath(new URL('./my-integration.json', dir)); } }}astro:build:done
Section titled “astro:build:done”上一个钩子: astro:build:generated
时机: 在生产构建(SSG 或 SSR)完成后。
用途: 访问生成的路由和资产进行扩展(例如,将内容复制到生成的 /assets 目录)。如果你打算转换生成的资源,我们建议探索 Vite 插件 API 和 通过 astro:config:setup 进行配置 来代替。
'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; /** @deprecated 使用 `assets` 映射以及新的 `astro:routes:resolved` 钩子 */ routes: IntegrationRouteData[]; assets: Map<string, URL[]>; logger: AstroIntegrationLogger;}) => void | Promise<void>;dir 选项
Section titled “dir 选项”类型: URL
一个构建输出目录的 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 选项
Section titled “routes 选项”所有生成的路由及其相关元数据的列表。
你可以参考下面完整的 IntegrationRouteData 类型,但最常见的属性是。
component- 相对于项目根的输入文件路径pathname- 输出文件的 URL(对于使用[dynamic]和[...spread]参数的路由未定义)。
assets 选项
Section titled “assets 选项”类型: Map<string, URL[]>
astro@5.0.0
包含了输出文件路径的链接,被 IntegrationResolvedRoute 的 pattern 属性分组。
pages 选项
Section titled “pages 选项”类型: { pathname: string }[]
一个包含了所有被生成页面的列表。每个条目是一个对象,且带有一个属性。
pathname- 页面的最终路径。
通过 全局增强 来扩展 IntegrationHooks 接口,可以将自定义钩子添加到集成中。
declare global { namespace Astro { export interface IntegrationHook { 'your:hook': (params: YourHookParameters) => Promise<void> } }}Astro 为未来的内置钩子保留了 astro: 前缀。请在命名时,为自定义钩子选择不同的前缀。
集成类型参考
Section titled “集成类型参考”以下类型可以从 astro 模块中导入:
import type { AstroIntegrationLogger, AstroIntegrationMiddleware, AstroMiddlewareInstance, AstroRenderer, ClientDirectiveConfig, HookParameters, IntegrationResolvedRoute, RedirectConfig, RouteData, RoutePart, RouteType, SSRComponentMetadata, SSRLoadedRenderer, SSRLoadedRendererValue, SSRManifest, ValidRedirectStatus, // 以下内容已被弃用: IntegrationRouteData,} from "astro";AstroIntegrationLogger
Section titled “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 }) => { // 执行一些行为 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 }) => { // 执行一些行为 logger.info("Integration ready."); }, "astro:build:done": ({ logger }) => { const buildLogger = logger.fork("astro-format/build"); // 执行一些行为 buildLogger.info("Build finished.") } } }}上面的示例将默认生成带有 [astro-format] 的日志,并在指定名字时生成带有 [astro-format/build] 的日志:
[astro-format] Integration ready.[astro-format/build] Build finished.AstroIntegrationMiddleware
Section titled “AstroIntegrationMiddleware”类型: { order: "pre" | "post"; entrypoint: string | URL; }
描述 由集成添加的中间件。
AstroIntegrationMiddleware.order
Section titled “AstroIntegrationMiddleware.order”类型: "pre" | "post"
指定中间件应该在其他中间件之前(pre)还是之后(post)运行。
AstroIntegrationMiddleware.entrypoint
Section titled “AstroIntegrationMiddleware.entrypoint”类型: string | URL
定义中间件的导入路径。
AstroMiddlewareInstance
Section titled “AstroMiddlewareInstance”类型: { onRequest?: MiddlewareHandler; }
一个对象,当项目的中间件函数存在时,包含一个使用该函数定义的 onRequest() 属性。
AstroRenderer
Section titled “AstroRenderer”类型: { name: string; clientEntrypoint?: string | URL; serverEntrypoint: string | URL; }
描述 由集成添加的组件框架渲染器。
AstroRenderer.name
Section titled “AstroRenderer.name”类型: string
组件框架渲染器的名称。
AstroRenderer.clientEntrypoint
Section titled “AstroRenderer.clientEntrypoint”类型: string | URL
定义在使用你的组件时,在客户端运行的渲染器的导入路径。
AstroRenderer.serverEntrypoint
Section titled “AstroRenderer.serverEntrypoint”类型: string | URL
定义渲染器的导入路径,该渲染器在每次使用组件时的服务器端请求或静态构建期间运行。
ClientDirectiveConfig
Section titled “ClientDirectiveConfig”类型: { name: string; entrypoint: string | URL; }
描述 由集成添加的自定义客户端指令。
ClientDirectiveConfig.name
Section titled “ClientDirectiveConfig.name”类型: string
指令触发事件的自定义名称。
ClientDirectiveConfig.entrypoint
Section titled “ClientDirectiveConfig.entrypoint”类型: string | URL
HookParameters
Section titled “HookParameters”你可以通过将钩子的名称传递给 HookParameters 实用工具类型来获取钩子参数的类型。
在以下示例中,输入了函数的 options 参数后,匹配到了 astro:config:setup 钩子 的参数:
import type { HookParameters } from 'astro';
function mySetup(options: HookParameters<'astro:config:setup'>) { options.updateConfig({ /* ... */ });}IntegrationResolvedRoute
Section titled “IntegrationResolvedRoute”具有重新映射属性的 RouteData 子集。
interface IntegrationResolvedRoute extends Pick< RouteData, 'generate' | 'params' | 'pathname' | 'segments' | 'type' | 'redirect' | 'origin' > & { pattern: RouteData['route']; patternRegex: RouteData['pattern']; entrypoint: RouteData['component']; isPrerendered: RouteData['prerender']; redirectRoute?: IntegrationResolvedRoute;}IntegrationResolvedRoute.pattern
Section titled “IntegrationResolvedRoute.pattern”允许你根据路由的路径来识别路由的类型。以下是与其格式(pattern)相关联的路径的一些示例:
src/pages/index.astro具有这样的格式/src/pages/blog/[...slug].astro具有这样的格式/blog/[...slug]src/pages/site/[blog]/[...slug].astro具有这样的格式/site/[blog]/[...slug]
IntegrationResolvedRoute.patternRegex
Section titled “IntegrationResolvedRoute.patternRegex”允许你读取一个正则表达式,该表达式用于将输入的 URL 与请求的路由进行匹配。
例如,[fruit]/about.astro 将生成这样的格式:/^\/([^/]+?)\/about\/?$/,那么,pattern.test("banana/about") 就会返回 true。
IntegrationResolvedRoute.entrypoint
Section titled “IntegrationResolvedRoute.entrypoint”源组件的 URL 路径名。
IntegrationResolvedRoute.isPrerendered
Section titled “IntegrationResolvedRoute.isPrerendered”确定该路径是否使用 按需渲染。对于配置了以下内容的项目,该值将为 true:
- 当路径不导出
const prerender = true时,output: 'static' - 当路径导出
const prerender = false时,output: 'server'
IntegrationResolvedRoute.redirectRoute
Section titled “IntegrationResolvedRoute.redirectRoute”类型: IntegrationResolvedRoute | undefined
当 IntegrationResolvedRoute.type 的值为 redirect 时,该值将成为 IntegrationResolvedRoute 重定向的目标。否则,该值将为 undefined。
RedirectConfig
Section titled “RedirectConfig”类型: string | { status: ValidRedirectStatus; destination: string; }
描述重定向的目标位置。该目标可以是一个字符串,或是一个包含状态码及其目标地址信息的对象。
RouteData
Section titled “RouteData”描述路由的相关信息。
RouteData.route
Section titled “RouteData.route”类型: string
定义当前路由模式。以下是一些与其模式关联的路径示例:
src/pages/index.astro会是/src/pages/blog/[...slug].astro会是/blog/[...slug]src/pages/site/[blog]/[...slug].astro会是/site/[blog]/[...slug]
RouteData.component
Section titled “RouteData.component”类型: string
指定源组件的 URL。
RouteData.generate()
Section titled “RouteData.generate()”类型: (data?: any) => string
该函数提供路由的可选参数,使用路由的格式对它们进行插值,然后返回路由的路径名。
例如,对于诸如 /blog/[...id].astro 这样的路由,generate() 函数将返回如下内容:
generate({ id: 'presentation' }) // 将输出 `/blog/presentation`RouteData.params
Section titled “RouteData.params”类型: string[]
允许你读取路由的 params。例如,当一个项目使用以下的 动态路由 /pages/[lang]/[...slug].astro时,该值将会是 ['lang', '...slug']。
RouteData.pathname
Section titled “RouteData.pathname”类型: string | undefined
对于常规的路由,该值即为路径名。而对于使用了 动态路由 的项目(例如:[dynamic] 或 [...spread]),该路径名将为 undefined。
RouteData.distURL
Section titled “RouteData.distURL”类型: URL[] | undefined
astro@5.0.0
定义此路由生成的物理文件的路径。当路由未进行预渲染时,该值为 undefined 或空数组。
RouteData.pattern
Section titled “RouteData.pattern”类型: RegExp
指定用于将输入 URL 与请求的路由进行匹配的正则表达式。
例如,给定一个 [fruit]/about.astro 路径,正则表达式将是 /^/([^/]+?)/about/?$/。使用 pattern.test("banana/about") 将会返回 true。
RouteData.segments
Section titled “RouteData.segments”类型: RoutePart[][]
允许你读取路由的 params,它有着额外的元数据。每个对象都包含了以下属性:
content:param的名称,dynamic: 路由是否为动态,spread: 动态路由是否使用了展开语法。
例如,以下的路由 /pages/[blog]/[...slug].astro 将会输出这样的分段(segments):
[ [ { content: 'pages', dynamic: false, spread: false } ], [ { content: 'blog', dynamic: true, spread: false } ], [ { content: '...slug', dynamic: true, spread: true } ]]RouteData.type
Section titled “RouteData.type”类型: RouteType
允许你识别 路由的类型。
RouteData.prerender
Section titled “RouteData.prerender”类型: boolean
确定路由是使用 按需渲染 还是在构建时静态预渲染。
另请参阅路由参考中的 prerendered。
RouteData.redirect
Section titled “RouteData.redirect”类型:* RedirectConfig | undefined
允许你访问要重定向到的路由。
RouteData.redirectRoute
Section titled “RouteData.redirectRoute”类型: RouteData | undefined
指定当 RouteData.type 为 redirect 时要重定向到的 RouteData。
RouteData.fallbackRoutes
Section titled “RouteData.fallbackRoutes”类型: RouteData[]
astro@3.5.6
定义一个 RouteData 列表,用于在 i18n.fallback 包含多个语言区域设置时进行回退。
RouteData.isIndex
Section titled “RouteData.isIndex”类型: boolean
指定路由是否为目录索引(例如 src/pages/index.astro、src/pages/blog/index.astro)。
RouteData.origin
Section titled “RouteData.origin”类型: 'internal' | 'external' | 'project'
astro@5.0.0
判断路由是来自 Astro 核心(internal)、集成(external)还是用户项目(project)。
RoutePart
Section titled “RoutePart”类型: { content: string; dynamic: boolean; spread: boolean; }
描述一个路由段。
RoutePart.content
Section titled “RoutePart.content”类型: string
指定路由的参数名称。例如:
about.astro的名称是about[slug].astro的名称是slug[...id].astro的名称是id
RoutePart.dynamic
Section titled “RoutePart.dynamic”类型: boolean
路由是否是动态的。
RoutePart.spread
Section titled “RoutePart.spread”类型: boolean
动态路由是否使用展开语法。
RouteType
Section titled “RouteType”类型: 'page' | 'endpoint' | 'redirect' | 'fallback'
支持的路由类型的联合类型
page: 位于文件系统中的路由,通常是一个 Astro 组件endpoint: 存在于文件系统中的路由,通常是一个暴露端点方法的 JS 文件redirect: 一个路由指向文件系统中存在的另一个路由fallback: 一个在文件系统中不存在的路由,需要通过其他方式处理,通常使用中间件
SSRComponentMetadata
Section titled “SSRComponentMetadata”类型: { propagation: PropagationHint; containsHead: boolean; }
描述服务器渲染的组件的构建元数据。
SSRComponentMetadata.propagation
Section titled “SSRComponentMetadata.propagation”类型: 'none' | 'self' | 'in-tree'
关于如何从该组件渲染 head 内容的描述,包括 Astro 运行时是否需要等待组件:
none:该组件不传递 head 内容。self:该组件追加 head 内容。in-tree:该组件的依赖树中的另一个组件追加 head 内容。
SSRComponentMetadata.containsHead
Section titled “SSRComponentMetadata.containsHead”类型:: boolean
确定组件是否包含头部内容。
SSRLoadedRenderer
Section titled “SSRLoadedRenderer”类型: { name: string; clientEntrypoint?: string | URL; ssr: SSRLoadedRendererValue; }
描述服务器可用的渲染器。这是 AstroRenderer 的一个子集,包含额外的属性。
SSRLoadedRenderer.ssr
Section titled “SSRLoadedRenderer.ssr”定义此框架的服务器使用的函数和配置。
SSRLoadedRendererValue
Section titled “SSRLoadedRendererValue”包含从特定 UI 框架在服务器上渲染组件所需的函数和配置。
SSRLoadedRendererValue.name
Section titled “SSRLoadedRendererValue.name”类型: string
指定渲染器的名称标识符。
SSRLoadedRendererValue.check()
Section titled “SSRLoadedRendererValue.check()”类型: AsyncRendererComponentFn<boolean>
确定渲染器是否应该处理该组件。
SSRLoadedRendererValue.renderToStaticMarkup()
Section titled “SSRLoadedRendererValue.renderToStaticMarkup()”类型: AsyncRendererComponentFn<{ html: string; attrs?: Record<string, string>; }>
在服务器上将框架组件渲染为静态 HTML 标记。
SSRLoadedRendererValue.supportsAstroStaticSlot
Section titled “SSRLoadedRendererValue.supportsAstroStaticSlot”类型: boolean
astro@2.5.0
指示渲染器是否支持 Astro 的静态插槽优化。当为 true 时,Astro 会防止移除岛屿内的嵌套插槽。
SSRLoadedRendererValue.renderHydrationScript()
Section titled “SSRLoadedRendererValue.renderHydrationScript()”类型: () => string
astro@4.1.0
返回一个特定于框架的水合脚本,该脚本必须在使用此渲染器的第一个组件之前注入到 HTML 中。
SSRManifest
Section titled “SSRManifest”一个包含构建配置和项目元数据的对象,服务器适配器在运行时使用它来提供按需渲染的页面。
SSRManifest.hrefRoot
Section titled “SSRManifest.hrefRoot”类型: string
astro@4.12.0
指定用于生成 URL 的根路径。
SSRManifest.adapterName
Section titled “SSRManifest.adapterName”类型: string
定义用于按需渲染的 服务器适配器 名称。
SSRManifest.routes
Section titled “SSRManifest.routes”类型: RouteInfo[]
此项目中可用路由的信息列表。每个条目包含以下属性。
RouteInfo.routeData
Section titled “RouteInfo.routeData”类型: RouteData
一个描述路由已知信息的对象。
RouteInfo.file
Section titled “RouteInfo.file”类型: string
指定构建路由入口点的文件路径。
RouteInfo.links
Section titled “RouteInfo.links”类型: string[]
定义此路由所需的 HTML link 元素 列表。
RouteInfo.scripts
Section titled “RouteInfo.scripts”类型: Array<{ children: string; stage: string } | { type: 'inline' | 'external'; value: string }>
定义与此路由关联的脚本列表。这包括具有 children 和 stage 属性的集成注入脚本,以及具有 type 和 value 属性的提升脚本。
RouteInfo.styles
Section titled “RouteInfo.styles”类型: Array<{ type: "inline"; content: string; } | { type: "external"; src: string; }>
astro@2.4.0
定义与此路由关联的样式表列表。这包括内联样式和样式表 URL。
SSRManifest.site
Section titled “SSRManifest.site”类型: string
指定 已配置的 site。
SSRManifest.base
Section titled “SSRManifest.base”类型: string
指定 已配置的 base 路径。
SSRManifest.userAssetsBase
Section titled “SSRManifest.userAssetsBase”类型: string | undefined
astro@5.3.1
指定在开发模式下用于用户生成资源(如脚本和样式)的基础路径。
SSRManifest.trailingSlash
Section titled “SSRManifest.trailingSlash”类型: AstroConfig['trailingSlash']
astro@3.5.4
指定开发模式和按需渲染页面中 尾部斜杠的配置行为。
SSRManifest.buildFormat
Section titled “SSRManifest.buildFormat”类型: NonNullable<AstroConfig['build']>['format']
astro@4.2.2
指定 已配置的输出文件格式。
SSRManifest.compressHTML
Section titled “SSRManifest.compressHTML”类型: boolean
astro@2.7.2
SSRManifest.assetsPrefix
Section titled “SSRManifest.assetsPrefix”类型: string | ({ fallback: string; } & Record<string, string>) | undefined
astro@2.3.1
SSRManifest.renderers
Section titled “SSRManifest.renderers”类型: SSRLoadedRenderer[]
服务器可使用的渲染器列表(例如 React、Vue、Svelte、MDX)。
SSRManifest.clientDirectives
Section titled “SSRManifest.clientDirectives”类型: Map<string, string>
astro@2.5.0
定义客户端指令名称(例如 load、visible)到其实现代码的映射。这包括 内置客户端指令 和 自定义客户端指令。
SSRManifest.entryModules
Section titled “SSRManifest.entryModules”类型: Record<string, string>
定义入口点到其输出文件路径的映射。
SSRManifest.inlinedScripts
Section titled “SSRManifest.inlinedScripts”类型: Map<string, string>
astro@4.5.0
定义脚本标识符到其内容的映射,用于将脚本内联到 HTML 输出中。
SSRManifest.assets
Section titled “SSRManifest.assets”类型: Set<string>
定义构建中所有资源文件的路径集合。
SSRManifest.componentMetadata
Section titled “SSRManifest.componentMetadata”类型: Map<string, SSRComponentMetadata>
astro@2.1.7
定义了组件标识符到其构建元数据的映射。每个条目包含有关 propagation 行为以及是否包含头部元素的信息。
SSRManifest.pageModule
Section titled “SSRManifest.pageModule”类型: { page: ImportComponentInstance; onRequest?: MiddlewareHandler; renderers: SSRLoadedRenderer[]; }
astro@2.7.0
指定页面模块的相关信息。
SSRManifest.pageModule.page()
Section titled “SSRManifest.pageModule.page()”类型: () => Promise<ComponentInstance>
一个用于检索页面组件实例的函数。
SSRManifest.pageModule.onRequest()
Section titled “SSRManifest.pageModule.onRequest()”astro@3.0.3
在用户项目中定义的 Astro 中间件函数。
SSRManifest.pageModule.renderers
Section titled “SSRManifest.pageModule.renderers”类型: SSRLoadedRenderer[]
服务器可以用于此页面的渲染器列表。
SSRManifest.pageMap
Section titled “SSRManifest.pageMap”类型: Map<string, () => Promise<typeof pageModule>>
定义组件路径到其可导入实例的映射关系。
SSRManifest.serverIslandMap
Section titled “SSRManifest.serverIslandMap”类型: Map<string, () => Promise<ComponentInstance>>
astro@4.12.0
定义服务器岛屿ID到其组件实例的映射。
SSRManifest.serverIslandNameMap
Section titled “SSRManifest.serverIslandNameMap”类型: Map<string, string>
astro@4.12.0
定义服务器岛屿组件路径到其指定名称的映射。
SSRManifest.key
Section titled “SSRManifest.key”类型: Promise<CryptoKey>
astro@4.13.4
确定用于加密服务器岛屿属性的 加密密钥。
SSRManifest.i18n
Section titled “SSRManifest.i18n”类型: SSRManifestI18n | undefined
astro@3.5.0
确定在项目中启用时已解析的 i18n 配置。
SSRManifest.i18n.strategy
Section titled “SSRManifest.i18n.strategy”类型: "manual" | "pathname-prefix-always" | "pathname-prefix-other-locales" | "pathname-prefix-always-no-redirect" | "domains-prefix-always" | "domains-prefix-other-locales" | "domains-prefix-always-no-redirect"
定义已配置的 i18n 路由策略。这决定了如何在 URL 中处理语言区域设置以及是否发生重定向。
SSRManifest.i18n.locales
Section titled “SSRManifest.i18n.locales”类型: Locales
确定 项目中配置的受支持语言环境 设置列表。
SSRManifest.i18n.defaultLocale
Section titled “SSRManifest.i18n.defaultLocale”类型: string
确定 项目中配置的默认语言环境。
SSRManifest.i18n.fallback
Section titled “SSRManifest.i18n.fallback”类型: Record<string, string> | undefined
确定 在 i18n.fallback 中配置 的语言环境到其回退语言环境的映射。
SSRManifest.i18n.fallbackType
Section titled “SSRManifest.i18n.fallbackType”类型: "redirect" | "rewrite"
确定 项目的配置回退策略。
SSRManifest.i18n.domainLookupTable
Section titled “SSRManifest.i18n.domainLookupTable”类型: Record<string, string>
已配置域名 到其关联语言区域的映射。
SSRManifest.middleware
Section titled “SSRManifest.middleware”类型: () => Promise<AstroMiddlewareInstance> | AstroMiddlewareInstance
astro@4.2.5
定义一个实例来加载中间件。
SSRManifest.actions
Section titled “SSRManifest.actions”类型: () => Promise<{ server: Record<string, ActionClient>; }> | { server: Record<string, ActionClient>; }
astro@5.4.2
一个对象,或者一个返回对象的函数,该对象具有一个 server 属性,该属性将 action 名称映射到它们的可调用函数。
SSRManifest.checkOrigin
Section titled “SSRManifest.checkOrigin”类型: boolean
astro@4.6.0
确定 安全配置中是否启用了来源检查。
SSRManifest.allowedDomains
Section titled “SSRManifest.allowedDomains”类型: Partial<RemotePattern>[]
指定在使用按需渲染时,传入请求 所允许的主机模式配置列表。
SSRManifest.sessionConfig
Section titled “SSRManifest.sessionConfig”类型: SessionConfig<TDriver> & { driverModule?: () => Promise<{ default: () => unstorage.Driver }>; }
astro@5.1.0
一个包含 已解析的会话配置 和定义正在使用的驱动程序的附加属性的对象。
SSRManifest.cacheDir
Section titled “SSRManifest.cacheDir”类型: string | URL
astro@5.2.0
指定 用于缓存构建产物的配置目录。
SSRManifest.srcDir
Section titled “SSRManifest.srcDir”类型: string | URL
astro@5.2.0
指定 Astro 读取站点的配置目录。
SSRManifest.outDir
Section titled “SSRManifest.outDir”类型: string | URL
astro@5.2.0
指定 用于写入最终构建文件的配置目录。
SSRManifest.publicDir
Section titled “SSRManifest.publicDir”类型: string | URL
astro@5.2.0
指定 用于静态资产的配置目录。
SSRManifest.buildClientDir
Section titled “SSRManifest.buildClientDir”类型: string | URL
astro@5.2.0
确定客户端构建产物(例如 JavaScript、CSS)在构建目录中的输出路径。
SSRManifest.buildServerDir
Section titled “SSRManifest.buildServerDir”类型: string | URL
astro@5.2.0
确定服务器端构建产物在构建目录中的输出路径。
SSRManifest.csp
Section titled “SSRManifest.csp”类型: SSRManifestCSP | undefined
astro@5.9.0
描述 内容安全策略配置。
SSRManifest.csp.cspDestination
Section titled “SSRManifest.csp.cspDestination”类型: 'adapter' | 'meta' | 'header' | undefined
指定 CSP 指令应作为 meta 元素注入、作为响应 header 注入,还是在 adapter 支持设置响应头时 由适配器注入。
SSRManifest.csp.algorithm
Section titled “SSRManifest.csp.algorithm”类型: 'SHA-256' | 'SHA-384' | 'SHA-512'
指定 配置的哈希函数。
SSRManifest.csp.scriptHashes
Section titled “SSRManifest.csp.scriptHashes”类型: string[]
指定项目脚本的生成哈希列表和外部脚本的 用户提供哈希。
SSRManifest.csp.scriptResources
Section titled “SSRManifest.csp.scriptResources”类型: string[]
指定一个有效源列表,该列表结合了 已配置的脚本资源 和 注入的脚本资源。
SSRManifest.csp.isStrictDynamic
Section titled “SSRManifest.csp.isStrictDynamic”类型: boolean
SSRManifest.csp.styleHashes
Section titled “SSRManifest.csp.styleHashes”类型: string[]
指定项目样式的生成哈希列表和外部样式的 用户提供哈希列表。
SSRManifest.csp.styleResources
Section titled “SSRManifest.csp.styleResources”类型: string[]
指定一个有效来源列表,该列表结合 了已配置的样式资源 和 注入的样式资源。
SSRManifest.csp.directives
Section titled “SSRManifest.csp.directives”类型: CspDirective[]
指定特定内容类型的 有效来源的配置列表。
SSRManifest.internalFetchHeaders
Section titled “SSRManifest.internalFetchHeaders”类型: Record<string, string>
astro@5.15.0
指定在渲染期间对内部 fetch 请求自动添加的 headers 请求头。
ValidRedirectStatus
Section titled “ValidRedirectStatus”类型: 301 | 302 | 303 | 307 | 308 | 300 | 304
支持的重定向状态码的联合类型。
已弃用的类型导入
Section titled “已弃用的类型导入”以下类型已被弃用,将在未来的主要版本中移除:
IntegrationRouteData
Section titled “IntegrationRouteData”在集成中使用的 RouteData 的精简版本。
type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin'> & { redirectRoute?: IntegrationRouteData;};redirectRoute
Section titled “redirectRoute”类型: IntegrationRouteData | undefined
当 RouteData.type 的值为 redirect 时,该值将包含要重定向到的路由的 IntegrationRouteData。否则,该值将为 undefined。
使用 astro add 安装
Section titled “使用 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()],})所有的集成都是按照配置的顺序运行的。例如,在 astro.config.* 中的数组 [react(), svelte()],react 将在 svelte 之前运行。
你的集成最好能以任何顺序运行。如果不行我们建议在文档中注明你的集成需要排在 integrations 配置数组的第一位或最后一位。
合并预置集成
Section titled “合并预置集成”一个集成也可以写成多个较小集成的集合。我们称这些集合为 预设。预设不是创建返回单个集成对象的工厂函数,而是返回集成对象的 数组。这对于从多个集成中构建复杂的功能非常有用。
integrations: [ // 示例:examplePreset() 将返回 [integrationOne, integrationTwo, ...etc] examplePreset()]- 构建你自己的 Astro 集成 - 由 FreeCodeCamp 的 Emmanuel Ohans 撰写
- Astro 集成模板 - 由 GitHub 上的 Florian Lefebvre 提供