Skip to content

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.

¥Quick API Reference

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: (pluginEntrypoint: string) => void;
injectScript: (stage: InjectedScriptStage, content: string) => void;
injectRoute: (injectedRoute: { pattern: string; entrypoint: string; prerender?: boolean }) => void;
createCodegenDir: () => URL;
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: { filename: string; content: string }) => URL;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
'astro:route:setup'?: (options: { route: RouteOptions; 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: vite.InlineConfig;
pages: Map<string, PageBuildData>;
target: 'client' | 'server';
updateConfig: (newConfig: vite.InlineConfig) => void;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>;
'astro:build:ssr'?: (options: {
manifest: SerializedSSRManifest;
entryPoints: Map<IntegrationRouteData, URL>;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
'astro:build:done'?: (options: {
dir: URL;
/** @deprecated Use the `assets` map and the new `astro:routes:resolved` hook */
routes: IntegrationRouteData[];
assets: Map<string, URL[]>;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
// ... any custom hooks from integrations
};
}

¥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:done

¥Next hook: astro:config:done

什么时候:初始化时,在 ViteAstro 配置 解析之前。

¥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.

'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: (pluginEntrypoint: string) => void;
addWatchFile: (path: URL | string) => void;
injectScript: (stage: InjectedScriptStage, content: string) => void;
injectRoute: (injectedRoute: { pattern: string; entrypoint: string; prerender?: boolean }) => void;
createCodegenDir: () => URL;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;

¥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 option

类型:'dev' | 'build' | 'preview' | 'sync'

¥Type: 'dev' | 'build' | 'preview' | 'sync'

  • dev - 项目使用 astro dev 执行

  • build - 项目使用 astro build 执行

  • preview - 项目使用 astro preview 执行

  • sync - 项目使用 astro sync 执行

¥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 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:

import bananaCSS from '@vitejs/official-banana-css-plugin';
export default {
name: 'banana-css-integration',
hooks: {
'astro:config:setup': ({ updateConfig }) => {
updateConfig({
vite: {
plugins: [bananaCSS()],
}
})
}
}
}

¥addRenderer option

类型:(renderer: AstroRenderer ) => void; 示例:sveltereactpreactvuesolid

¥Type: (renderer: AstroRenderer ) => void; Examples: 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 回调 就是一个典型的例子。

Added in: astro@5.0.0

函数 clientEntrypointserverEntrypoint 接受 URL

¥The functions clientEntrypoint and serverEntrypoint accept a URL.

¥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:

// Must be an absolute path!
addWatchFile('/home/user/.../my-config.json');
addWatchFile(new URL('./tailwind.config.js', config.root));

¥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:

astro.config.mjs
import { defineConfig } from 'astro/config';
import clickDirective from './astro-click-directive/register.js'
// https://astro.build/config
export default defineConfig({
integrations: [
clickDirective()
],
});
astro-click-directive/register.js
/**
* @type {() => import('astro').AstroIntegration}
*/
export default () => ({
name: "client:click",
hooks: {
"astro:config:setup": ({ addClientDirective }) => {
addClientDirective({
name: "click",
entrypoint: "./astro-click-directive/click.js",
});
},
},
});
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 })
}

你还可以在库的类型定义文件中添加指令的类型:

¥You can also add types for the directives in your library’s type definition file:

astro-click-directive/index.d.ts
import 'astro'
declare module 'astro' {
interface AstroClientDirectives {
'client:click'?: boolean
}
}

¥addDevToolbarApp option

Added in: astro@3.4.0

类型:(pluginEntrypoint: string) => void;

¥Type: (pluginEntrypoint: string) => void;

添加 自定义开发工具栏应用

¥Adds a custom dev toolbar app.

用法示例:

¥Example usage:

astro.config.mjs
import { defineConfig } from 'astro/config';
import devToolbarIntegration from './astro-dev-toolbar-app/integration.js'
// https://astro.build/config
export default defineConfig({
integrations: [
devToolbarIntegration()
],
});
astro-dev-toolbar-app/integration.js
/**
* @type {() => import('astro').AstroIntegration}
*/
export default () => ({
name: "dev-toolbar-app",
hooks: {
"astro:config:setup": ({ addDevToolbarApp }) => {
addDevToolbarApp("./astro-dev-toolbar-app/plugin.js");
},
},
});
astro-dev-toolbar-app/plugin.js
/**
* @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 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).

@my-package/integration.js
/**
* @type {() => import('astro').AstroIntegration}
*/
export default () => ({
name: "my-middleware-package",
hooks: {
"astro:config:setup": ({ addMiddleware }) => {
addMiddleware({
entrypoint: '@my-package/middleware',
order: 'pre'
});
},
},
});

中间件是在具有 onRequest 函数的包中定义的,与用户定义的中间件一样。

¥Middleware is defined in a package with an onRequest function, as with user-defined middleware.

@my-package/middleware.js
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();
});

Added in: astro@5.0.0

该函数还接受 URL 作为 entrypoint

¥The function also accepts a URL for entrypoint:

@my-package/integration.js
/**
* @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 option

类型:({ pattern: string; entrypoint: string; pattern?: boolean }) => void;

¥Type: ({ pattern: string; entrypoint: string; pattern?: boolean }) => 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 接受一个带有 patternentrypoint 的对象。

¥injectRoute takes an object with a pattern and an entrypoint.

  • pattern - 其中浏览器中应输出路由,例如 /foo/barpattern 可以使用 Astro 的文件路径语法来表示动态路由,例如 /foo/[bar]/foo/[...bar]。请注意,pattern 中不需要文件扩展名。

  • entrypoint - 指向 .astro 页面或 .js/.ts 路由处理程序的裸模块说明符,用于处理 pattern 中表示的路由。

  • prerender - 如果 Astro 无法检测到你的 prerender 导出,则设置布尔值。

¥Example usage

injectRoute({
// Use Astro’s pattern syntax for dynamic routes.
pattern: '/subfolder/[dynamic]',
// Use relative path syntax for a local route.
entrypoint: './src/dynamic-page.astro',
// Use only if Astro can't detect your prerender export
prerender: false
});

对于设计为安装在其他项目中的集成,请使用其包名称来引用路由入口点。以下示例显示了作为 @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:

injectRoute({
pattern: '/fancy-dashboard',
entrypoint: '@fancy/dashboard/dashboard.astro'
});

将你的包(本例中为 @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:

package.json
{
"name": "@fancy/dashboard",
// ...
"exports": { "./dashboard.astro": "./dashboard.astro" }
}

Added in: astro@5.0.0

该函数还接受 URL 作为 entrypoint

¥The function also accepts a URL for entrypoint:

injectRoute({
pattern: '/fancy-dashboard',
entrypoint: new URL('./dashboard.astro', import.meta.url)
});

¥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 阶段的主要用途是在每个页面中注入一个 CSS import,供 Vite 优化解析:

    injectScript('page-ssr', 'import "global-styles.css";');

类型:() => URL;

¥Type: () => URL;

Added in: astro@5.0.0

创建 <root>/.astro/integrations/<normalized_integration_name> 文件夹并返回其路径的函数。

¥A function that creates the <root>/.astro/integrations/<normalized_integration_name> folder and returns its path.

它允许你拥有一个专用文件夹,避免与另一个集成或 Astro 本身发生冲突。此目录是通过调用此函数创建的,因此可以安全地直接将文件写入其中:

¥It allows you to have a dedicated folder, avoiding conflicts with another integration or Astro itself. This directory is created by calling this function so it’s safe to write files to it directly:

my-integration.ts
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')
}
}
}
Added in: astro@5.0.0

上一个钩子:astro:config:setup

¥Previous hook: astro:config:setup

下一个钩子:astro:config:done

¥Next hook: astro:config:done

什么时候:在 astro dev 中,如果基于文件的路由发生变化(添加/删除/更新),它也会运行。

¥When: In astro dev, it also runs if a file based route changes (added/removed/updated).

为什么:要访问路由及其元数据

¥Why: To access routes and their metadata

'astro:routes:resolved'?: (options: {
routes: IntegrationResolvedRoute[];
logger: AstroIntegrationLogger;
}) => void | Promise<void>;

¥routes option

类型:IntegrationResolvedRoute[]

¥Type: IntegrationResolvedRoute[]

所有路由及其相关元数据的列表。

¥A list of all routes with their associated metadata.

示例用法:

¥Example use:

my-integration.mjs
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)
},
}
}
}
IntegrationResolvedRoute 型号参考
标题部分 IntegrationResolvedRoute 型号参考

¥IntegrationResolvedRoute type reference

interface IntegrationResolvedRoute {
/**
* The current **pattern** of the route. For example:
* - `src/pages/index.astro` has a pattern of `/`
* - `src/pages/blog/[...slug].astro` has a pattern of `/blog/[...slug]`
* - `src/pages/site/[blog]/[...slug].astro` has a pattern of `/site/[blog]/[...slug]`
*/
pattern: RouteData['route'];
/**
* * regex used for matching an input URL against a requested route
* ex. "[fruit]/about.astro" will generate the pattern: /^\/([^/]+?)\/about\/?$/
* where pattern.test("banana/about") is "true"
* * ## Example
* * ```js
* if (route.pattern.test('/blog')) {
* // do something
* }
* ```
*/
patternRegex: RouteData['pattern'];
/**
* Source component URL
*/
entrypoint: RouteData['component'];
/**
* Whether the route is prerendered or not
*/
isPrerendered: RouteData['prerender'];
/**
* The {@link IntegrationResolvedRoute} to redirect to. It's present when `IntegrationResolvedRoute.type` is `redirect`.
*/
redirectRoute?: IntegrationResolvedRoute;
/**
* @param {any} data The optional parameters of the route
* * @description
* A function that accepts a list of params, interpolates them with the route pattern, and returns the path name of the route.
* * ## Example
* * For a route such as `/blog/[...id].astro`, the `generate` function would return something like this:
* * ```js
* console.log(generate({ id: 'presentation' })) // will log `/blog/presentation`
* ```
*/
generate: (data?: any) => string;
/**
* Dynamic and spread route params
* ex. "/pages/[lang]/[...slug].astro" will output the params ['lang', '...slug']
*/
params: string[];
/**
* Output URL pathname where this route will be served
* note: will be undefined for [dynamic] and [...spread] routes
*/
pathname?: string;
/**
* Similar to the "params" field, but with more associated metadata. For example, for `/site/[blog]/[...slug].astro`, the segments are:
* * 1. `{ content: 'site', dynamic: false, spread: false }`
* 2. `{ content: 'blog', dynamic: true, spread: false }`
* 3. `{ content: '...slug', dynamic: true, spread: true }`
*/
segments: RoutePart[][];
/**
* * The type of the route. It can be:
* - `page`: a route that lives in the file system, usually an Astro component
* - `endpoint`: a route that lives in the file system, usually a JS file that exposes endpoints methods
* - `redirect`: a route points to another route that lives in the file system
* - `fallback`: a route that doesn't exist in the file system that needs to be handled with other means, usually the middleware
*/
type: RouteType;
/**
* The route to redirect to. It holds information regarding the status code and its destination.
*/
redirect?: RedirectConfig;
/**
* Whether the route comes from Astro core, an integration or the user's project
*/
origin: 'internal' | 'external' | 'project';
}

上一个钩子: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.

'astro:config:done'?: (options: {
config: AstroConfig;
setAdapter: (adapter: AstroAdapter) => void;
injectTypes: (injectedType: { filename: string; content: string }) => URL;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;

¥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 option

类型:(adapter: AstroAdapter) => void;

¥Type: (adapter: AstroAdapter) => void;

使集成成为适配器。在 适配器 API 中阅读更多内容。

¥Makes the integration an adapter. Read more in the adapter API.

¥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.

const path = injectTypes({
filename: "types.d.ts",
content: "declare module 'virtual:integration' {}"
})
console.log(path) // URL

上一个钩子: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, or enable support for refreshing the content layer.

'astro:server:setup'?: (options: {
server: vite.ViteDevServer;
refreshContent: (options: {
loaders?: Array<string>;
context?: Record<string, any>;
}) => Promise<void>;
}) => void | Promise<void>;

¥server option

类型:ViteDevServer

¥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:

export default {
name: 'partytown',
hooks: {
'astro:server:setup': ({ server }) => {
server.middlewares.use(
function middleware(req, res, next) {
// handle requests
}
);
}
}
}

¥refreshContent option

类型:(options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>

¥Type: (options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>

Added in: astro@5.0.0

用于集成在 astro dev 期间触发内容层更新的函数。例如,这可用于在开发期间注册 webhook 端点,或打开 CMS 的套接字以监听更改。

¥A function for integrations to trigger an update to the content layer during astro dev. This can be used, for example, to register a webhook endpoint during dev, or to open a socket to a CMS to listen for changes.

默认情况下,refreshContent 将刷新所有集合。你可以选择传递 loaders 属性,它是加载器名称的数组。如果提供,则仅刷新使用这些加载器的集合。例如,CMS 集成可以使用此属性仅刷新其自己的集合。

¥By default, refreshContent will refresh all collections. You can optionally pass a loaders property, which is an array of loader names. If provided, only collections that use those loaders will be refreshed. For example, A CMS integration could use this property to only refresh its own collections.

你还可以将 context 对象传递给加载器。这可用于传递任意数据,例如 webhook 主体或来自 websocket 的事件。

¥You can also pass a context object to the loaders. This can be used to pass arbitrary data such as the webhook body, or an event from the websocket.

my-integration.ts
{
name: 'my-integration',
hooks: {
'astro:server:setup': async ({ server, refreshContent }) => {
// Register a dev server webhook endpoint
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 主体。有关更多信息,请参阅 refreshContextData 属性。

¥The loader can then access the refreshContextData property to get the webhook body. See the refreshContextData property for more information.

上一个钩子: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.

'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>;

¥address option

类型:AddressInfo

¥Type: AddressInfo

Node.js Net 模块 提供的地址、系列和端口号。

¥The address, family and port number supplied by the Node.js Net module.

上一个钩子:astro:server:start

¥Previous hook: astro:server:start

什么时候:就在开发服务器关闭之后。

¥When: Just after the dev server is closed.

为什么:要运行你可能在 astro:server:setupastro:server:start 钩子期间触发的任何清理事件。

¥Why: To run any cleanup events you may trigger during the astro:server:setup or astro:server:start hooks.

'astro:server:done'?: () => void | Promise<void>;

上一个钩子: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:start'?: () => void | Promise<void>;

上一个钩子: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:setup'?: (options: {
vite: vite.InlineConfig;
pages: Map<string, PageBuildData>;
target: 'client' | 'server';
updateConfig: (newConfig: vite.InlineConfig) => void;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;

上一个钩子: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:generated'?: (options: { dir: URL }) => void | Promise<void>;

上一个钩子: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:ssr'?: (options: {
manifest: SerializedSSRManifest,
entryPoints: Map<IntegrationRouteData, URL>,
middlewareEntryPoint: URL
}) => void | Promise<void>;

上一个钩子: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.

'astro:build:done'?: (options: {
dir: URL;
/** @deprecated Use the `assets` map and the new `astro:routes:resolved` hook */
routes: IntegrationRouteData[];
assets: Map<string, URL[]>;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;

¥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.

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();
// Use fileURLToPath to get a valid, cross-platform absolute path string
const outFile = fileURLToPath(new URL('./my-integration.json', dir));
await writeFile(outFile, JSON.stringify(metadata));
}
}
}
}

¥routes option

类型:IntegrationRouteData[]

¥Type: IntegrationRouteData[]

所有生成的路由及其关联元数据的列表。

¥A list of all generated routes alongside their associated metadata.

你可以参考下面的完整 IntegrationRouteData 类型,但最常见的属性是:

¥You can reference the full IntegrationRouteData type below, but the most common properties are:

  • component - 相对于项目根目录的输入文件路径

  • pathname - 输出文件 URL(对于使用 [dynamic][...spread] 参数的路由未定义)

IntegrationRouteData 型号参考
标题部分 IntegrationRouteData 型号参考

¥IntegrationRouteData type reference

interface IntegrationRouteData {
/**
* The type of the route. It can be:
*
* - `page`: a route that lives in the file system, usually an Astro component
* - `endpoint`: a route that lives in the file system, usually a JS file that exposes endpoints methods
* - `redirect`: a route that points to another route that lives in the file system
* - `fallback`: a route that doesn't exist in the file system and needs to be handled with other means, usually middleware
*/
type: 'page' | 'endpoint' | 'redirect' | 'fallback';
/** Source component URL */
component: string;
/**
* Output URL pathname where this route will be served
* note: will be undefined for [dynamic] and [...spread] routes
*/
pathname?: string;
/**
* regex used for matching an input URL against a requested route
* ex. "[fruit]/about.astro" will generate the pattern: /^\/([^/]+?)\/about\/?$/
* where pattern.test("banana/about") is "true"
*/
pattern: RegExp;
/**
* Dynamic and spread route params
* ex. "/pages/[lang]/[..slug].astro" will output the params ['lang', '...slug']
*/
params: string[];
/**
* Similar to the "params" field, but with more associated metadata
* ex. "/pages/[lang]/index.astro" will output the segments
* [[ { content: 'lang', dynamic: true, spread: false } ]]
*/
segments: { content: string; dynamic: boolean; spread: boolean; }[][];
/**
* A function that accepts a list of params, interpolates them with the route pattern, and returns the path name of the route.
*
* ## Example
*
* For a route such as `/blog/[...id].astro`, the `generate` function would return something like this:
*
* ```js
* console.log(generate({ id: 'presentation' })) // will log `/blog/presentation`
* ```
* This is typically for internal use, so call with caution!
*/
generate: (data?: any) => string;
/**
* Whether the route is prerendered or not.
*/
prerender: boolean;
/**
* The paths of the physical files emitted by this route. When a route **isn't** prerendered, the value is either `undefined` or an empty array.
*/
distURL?: URL[];
/**
* The route to redirect to. It holds information regarding the status code and its destination.
*/
redirect?: RedirectConfig;
/**
* The `IntegrationRouteData` to redirect to. It's present when `RouteData.type` is `redirect`.
*/
redirectRoute?: IntegrationRouteData;
}

¥assets option

Added in: astro@5.0.0

类型:Map<string, URL[]>

¥Type: Map<string, URL[]>

包含输出文件路径的 URL,按 IntegrationResolvedRoute pattern 属性分组。

¥Contains URLs to output files paths, grouped by IntegrationResolvedRoute pattern property.

¥pages option

类型:{ pathname: string }[]

¥Type: { pathname: string }[]

所有生成的页面的列表。它是一个具有一个属性的对象。

¥A list of all generated pages. It is an object with one property.

  • pathname - 页面的最终路径。

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.

'astro:route:setup'?: (options: { route: RouteOptions }) => void | Promise<void>;

¥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".

类型:boolean
默认:undefined

¥Type: boolean
Default: undefined

Added in: 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.

astro.config.mjs
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 模式按需渲染。

¥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 static mode, and on-demand rendered for server mode.

¥Custom hooks

可以通过 全局增强 扩展 IntegrationHooks 接口,将自定义钩子添加到集成中。

¥Custom hooks can be added to integrations by extending the IntegrationHooks interface through global augmentation.

declare global {
namespace Astro {
export interface IntegrationHook {
'your:hook': (params: YourHookParameters) => Promise<void>
}
}
}

Astro 为未来的内置钩子保留了 astro: 前缀。命名自定义钩子时,请选择不同的前缀。

¥Astro reserves the astro: prefix for future built-in hooks. Please choose a different prefix when naming your custom hook.

你可以通过将钩子的名称传递给 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:

import type { HookParameters } from 'astro';
function mySetup(options: HookParameters<'astro:config:setup'>) {
options.updateConfig({ /* ... */ });
}

允许使用 astro add 安装

标题部分 允许使用 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:

{
"name": "example",
"keywords": ["astro-integration"],
}

完成 将你的集成发布到 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:

astro.config.mjs
import { defineConfig } from 'astro/config';
import example from 'example';
export default defineConfig({
integrations: [example()],
})

Astro 日志器的实例,可用于写入日志。该日志器使用通过 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.

integration.ts
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 消息:

¥The example above will log a message that includes the provided info message:

终端窗口
[astro-format] Integration ready.

要使用不同标签记录某些消息,请使用 .fork 方法指定默认 name 的替代方法:

¥To log some messages with a different label, use the .fork method to specify an alternative to the default name:

integration.ts
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] 的日志:

¥The example above will produce logs with [astro-format] by default, and [astro-format/build] when specified:

终端窗口
[astro-format] Integration ready.
[astro-format/build] Build finished.

¥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.

将集成合并到预设中

标题部分 将集成合并到预设中

¥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.

integrations: [
// Example: where examplePreset() returns: [integrationOne, integrationTwo, ...etc]
examplePreset()
]

¥Community Resources

Astro 中文网 - 粤ICP备13048890号