Skip to content

编程 Astro API(实验性)

如果你在运行 Astro 时需要更多控制,"astro" 包会导出 API 以编程方式运行 CLI 命令。

¥If you need more control when running Astro, the "astro" package exports APIs to programmatically run the CLI commands.

这些 API 是实验性的,它们的 API 签名可能会发生变化。任何更新都会在 Astro 变更日志 中提及,并且下面的信息将始终显示当前的最新信息。

¥These APIs are experimental and their API signature may change. Any updates will be mentioned in the Astro changelog and the information below will always show the current, up-to-date information.

以下所有命令 API 使用 AstroInlineConfig 类型。它从用户 Astro 配置 类型扩展而来:

¥The AstroInlineConfig type is used by all of the command APIs below. It extends from the user Astro config type:

interface AstroInlineConfig extends AstroUserConfig {
configFile?: string | false;
mode?: string;
logLevel?: "debug" | "info" | "warn" | "error" | "silent";
}

类型:string | false
默认:undefined

¥Type: string | false
Default: undefined

Astro 配置文件的自定义路径。

¥A custom path to the Astro config file.

如果该值未定义(默认)或未设置,Astro 将搜索相对于 rootastro.config.(js,mjs,ts,mts) 文件,并在找到时加载配置文件。

¥If this value is undefined (default) or unset, Astro will search for an astro.config.(js,mjs,ts,mts) file relative to the root and load the config file if found.

如果设置了相对路径,则会根据 root 选项进行解析。

¥If a relative path is set, it will resolve based on the root option.

设置为 false 以禁用加载任何配置文件。

¥Set to false to disable loading any config files.

与加载的用户配置合并时,传入此对象的内联配置将具有最高优先级。

¥The inline config passed in this object will take highest priority when merging with the loaded user config.

类型:string
默认:运行 astro dev 时为 "development",运行 astro build
时为 "production"

¥Type: string
Default: "development" when running astro dev, "production" when running astro build

Added in: astro@5.0.0

开发或构建站点时使用的模式(例如 "production""testing")。

¥The mode used when developing or building your site (e.g. "production", "testing").

此值使用 the --mode flag when the astro build or astro dev commands are run to determine the value of import.meta.env.MODE. This also determines which .env files are loaded, and therefore the values of astro:env. See the environment variables page 传递给 Vite 以获取更多详细信息。

¥This value is passed to Vite using the --mode flag when the astro build or astro dev commands are run to determine the value of import.meta.env.MODE. This also determines which .env files are loaded, and therefore the values of astro:env. See the environment variables page for more details.

要输出基于开发的版本,你可以使用 --devOutput 标志 运行 astro build

¥To output a development-based build, you can run astro build with the --devOutput flag.

类型:"debug" | "info" | "warn" | "error" | "silent"
默认:"info"

¥Type: "debug" | "info" | "warn" | "error" | "silent"
Default: "info"

用于过滤 Astro 记录的消息的日志记录级别。

¥The logging level to filter messages logged by Astro.

  • "debug":记录一切,包括嘈杂的调试诊断。

  • "info":记录信息性消息、警告和错误。

  • "warn":记录警告和错误。

  • "error":仅记录错误。

  • "silent":没有日志记录。

类型:(inlineConfig: AstroInlineConfig) => Promise<DevServer>

¥Type: (inlineConfig: AstroInlineConfig) => Promise<DevServer>

astro dev 类似,它运行 Astro 的开发服务器。

¥Similar to astro dev, it runs Astro’s development server.

import { dev } from "astro";
const devServer = await dev({
root: "./my-project",
});
// Stop the server if needed
await devServer.stop();
export interface DevServer {
address: AddressInfo;
handle: (req: http.IncomingMessage, res: http.ServerResponsehttp.IncomingMessage) => void;
watcher: vite.FSWatcher;
stop(): Promise<void>;
}

类型:AddressInfo

¥Type: AddressInfo

开发服务器正在监听的地址。

¥The address the dev server is listening on.

此属性包含 Node 的 net.Server#address() method 返回的值。

¥This property contains the value returned by Node’s net.Server#address() method.

类型:(req: http.IncomingMessage, res: http.ServerResponsehttp.IncomingMessage) => void

¥Type: (req: http.IncomingMessage, res: http.ServerResponsehttp.IncomingMessage) => void

原始 Node HTTP 请求的句柄。你可以使用 http.IncomingMessagehttp.ServerResponse 调用 handle(),而不是通过网络发送请求。

¥A handle for raw Node HTTP requests. You can call handle() with an http.IncomingMessage and an http.ServerResponse instead of sending a request through the network.

类型:vite.FSWatcher

¥Type: vite.FSWatcher

Vite 的开发服务器 公开的 Chokidar 文件监视器

¥The Chokidar file watcher as exposed by Vite’s development server.

类型:Promise<void>

¥Type: Promise<void>

停止开发服务器。这将关闭所有空闲连接并停止监听新连接。

¥Stops the development server. This closes all idle connections and stops listening for new connections.

返回一个 Promise,该 Promise 会在所有待处理的请求都已完成并且所有空闲连接都已关闭后解析。

¥Returns a Promise that resolves once all pending requests have been fulfilled and all idle connections have been closed.

类型:(inlineConfig: AstroInlineConfig, options?: BuildOptions) => Promise<void>

¥Type: (inlineConfig: AstroInlineConfig, options?: BuildOptions) => Promise<void>

astro build 类似,它构建你的站点以进行部署。

¥Similar to astro build, it builds your site for deployment.

import { build } from "astro";
await build({
root: "./my-project",
});
export interface BuildOptions {
devOutput?: boolean;
teardownCompiler?: boolean;
}

类型:boolean
默认:false

¥Type: boolean
Default: false

Added in: astro@5.4.0

输出类似于 astro dev 中转换的代码的基于开发的构建。这可用于测试仅构建问题并包含其他调试信息。

¥Output a development-based build similar to code transformed in astro dev. This can be useful to test build-only issues with additional debugging information included.

类型:boolean
默认:true

¥Type: boolean
Default: true

Added in: astro@5.4.0

构建后拆卸编译器 WASM 实例。这可以在构建一次时提高性能,但如果连续构建多次,可能会导致性能下降。

¥Teardown the compiler WASM instance after build. This can improve performance when building once but may cause a performance hit if building multiple times in a row.

在同一执行中构建多个项目时(例如在测试期间),禁用此选项可以大大提高性能并减少峰值内存使用量,但代价是持续内存使用量更高。

¥When building multiple projects in the same execution (e.g. during tests), disabling this option can greatly increase performance and reduce peak memory usage at the cost of higher sustained memory usage.

类型:(inlineConfig: AstroInlineConfig) => Promise<PreviewServer>

¥Type: (inlineConfig: AstroInlineConfig) => Promise<PreviewServer>

astro preview 类似,它会启动本地服务器来为你的构建输出提供服务。

¥Similar to astro preview, it starts a local server to serve your build output.

如果配置中未设置适配器,则预览服务器将仅提供构建的静态文件。如果配置中设置了适配器,则预览服务器由适配器提供。适配器不需要提供预览服务器,因此根据你选择的适配器,此功能可能无法使用。

¥If no adapter is set in the configuration, the preview server will only serve the built static files. If an adapter is set in the configuration, the preview server is provided by the adapter. Adapters are not required to provide a preview server, so this feature may not be available depending on your adapter of choice.

import { preview } from "astro";
const previewServer = await preview({
root: "./my-project",
});
// Stop the server if needed
await previewServer.stop();
export interface PreviewServer {
host?: string;
port: number;
closed(): Promise<void>;
stop(): Promise<void>;
}

类型:string

¥Type: string

服务器监听连接的主机。

¥The host where the server is listening for connections.

允许适配器不设置此字段。host 的值是特定于实现的。

¥Adapters are allowed to leave this field unset. The value of host is implementation-specific.

类型:number

¥Type: number

服务器监听连接的端口。

¥The port where the server is listening for connections.

类型:Promise<void>

¥Type: Promise<void>

要求预览服务器关闭、停止接受请求并断开空闲连接。

¥Asks the preview server to close, stop accepting requests, and drop idle connections.

发送关闭请求后,返回的 Promise 会解析。这并不意味着服务器已关闭。如果你需要确保服务器已完全关闭,请使用 closed() 方法。

¥The returned Promise resolves when the close request has been sent. This does not mean that the server has closed yet. Use the closed() method if you need to ensure the server has fully closed.

类型:Promise<void>

¥Type: Promise<void>

返回一个 Promise,它会在服务器关闭后解析,如果服务器上发生错误则会拒绝。

¥Returns a Promise that will resolve once the server is closed and reject if an error happens on the server.

类型:(inlineConfig: AstroInlineConfig) => Promise<void>

¥Type: (inlineConfig: AstroInlineConfig) => Promise<void>

astro sync 类似,它为所有 Astro 模块生成 TypeScript 类型。

¥Similar to astro sync, it generates TypeScript types for all Astro modules.

import { sync } from "astro";
await sync({
root: "./my-project",
});

类型:<T extends AstroConfig | AstroInlineConfig>(config: T, overrides: DeepPartial<T>) => T

¥Type: <T extends AstroConfig | AstroInlineConfig>(config: T, overrides: DeepPartial<T>) => T

Added in: astro@5.4.0

astro/config 导入,将部分 Astro 配置合并到现有的有效 Astro 配置之上。

¥Imported from astro/config, merges a partial Astro configuration on top of an existing, valid, Astro configuration.

mergeConfig() 接受 Astro 配置对象和部分配置(任何一组有效的 Astro 配置选项),并返回结合两个值的有效 Astro 配置,以便:

¥mergeConfig() accepts an Astro config object and a partial config (any set of valid Astro config options), and returns a valid Astro config combining both values such that:

  • 数组是连接的(包括集成和 remark 插件)。

  • 对象以递归方式合并。

  • Vite 选项使用 Vite 自己的 mergeConfig 函数 和默认 isRoot 标志合并。

  • 可以作为函数提供的选项被封装到新函数中,这些新函数以相同的规则递归合并来自两个配置的返回值。

  • 所有其他选项将覆盖现有配置。

import { mergeConfig } from "astro/config";
mergeConfig(
{
output: 'static',
site: 'https://example.com',
integrations: [tailwind()],
server: ({command}) => ({
port: command === 'dev' ? 4321 : 1234,
}),
build: {
client: './custom-client',
},
},
{
output: 'server',
base: '/astro',
integrations: [mdx()],
server: ({command}) => ({
host: command === 'dev' ? 'localhost' : 'site.localhost',
}),
build: {
server: './custom-server',
},
}
);
// Result is equivalent to:
{
output: 'server',
site: 'https://example.com',
base: '/astro',
integrations: [tailwind(), mdx()],
server: ({command}) => ({
port: command === 'dev' ? 4321 : 1234,
host: command === 'dev' ? 'localhost' : 'site.localhost',
}),
build: {
client: './custom-client',
server: './custom-server',
},
}

类型:(userConfig: any, root: string, cmd: string): Promise<AstroConfig>

¥Type: (userConfig: any, root: string, cmd: string): Promise<AstroConfig>

Added in: astro@5.4.0

astro/config 导入,验证对象,就好像它是从 astro.config.mjs 导出并由 Astro 导入的一样。

¥Imported from astro/config, validates an object as if it was exported from astro.config.mjs and imported by Astro.

它采用以下参数:

¥It takes the following arguments:

  • 要验证的配置。

  • 项目的根目录。

  • 正在执行的 Astro 命令(builddevsync 等)

返回的 promise 解析为经过验证的配置,并填充了适合给定 Astro 命令的所有默认值。

¥The returned promise resolves to the validated configuration, filled with all default values appropriate for the given Astro command.

import { validateConfig } from "astro/config";
const config = await validateConfig({
integrations: [tailwind()],
}, "./my-project", "build");
// defaults are applied
await rm(config.outDir, { recursive: true, force: true });
Astro v5.5 中文网 - 粤ICP备13048890号