跳转到内容

编程式 Astro API(实验性)

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

这些 API 是实验性的,其 API 签名可能会更改。任何更新都会在 Astro changelog 中提及,下面的信息将始终显示最新的信息。

AstroInlineConfig

AstroInlineConfig 类型由以下的所有命令 API 使用。它继承自用户的 Astro 配置 类型:

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

configFile

类型: string | false
默认值: undefined

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

如果这个值为 undefined(默认值) 或 unset,那么 Astro 将尝试搜索一个相对 root 目录的 astro.config.(js,mjs,ts,mts) 文件,如果找到的话,则加载配置文件。

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

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

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

mode

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

添加于: astro@5.0.0

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

当运行 astro buildastro dev 命令时,这个值会使用 --mode 标志 传递给 Vite,以确定 import.meta.env.MODE 的值。这也决定了加载哪些 .env 文件,从而决定了 astro:env 的值。有关更多详细信息,请参阅 环境变量 页面。

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

logLevel

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

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

  • "debug":记录所有内容,包括嘈杂的调试诊断。
  • "info":记录信息性消息、警告和错误。
  • "warn":记录警告和错误。
  • "error":仅记录错误。
  • "silent":无日志记录。

dev()

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

astro dev 相似,用于运行 Astro 的开发服务器。

import { dev } from "astro";

const devServer = await dev({
  root: "./my-project",
});

// 如需停止服务器:
await devServer.stop();

DevServer

export interface DevServer {
	address: AddressInfo;
	handle: (req: http.IncomingMessage, res: http.ServerResponse<http.IncomingMessage>) => void;
	watcher: vite.FSWatcher;
	stop(): Promise<void>;
}

address

类型: AddressInfo

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

此属性包含 Node 的 [net.Server#address() 方法](https://nodejs.org/api/net.html#serveraddress)。

handle()

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

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

watcher

类型: vite.FSWatcher

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

stop()

类型: Promise<void>

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

返回一个 Promise,该 Promise 在完成所有待处理请求并关闭所有空闲连接后结束。

build()

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

astro build 相似,用于构建你的站点以进行部署。

import { build } from "astro";

await build({
  root: "./my-project",
});

BuildOptions

export interface BuildOptions {
	devOutput?: boolean;
	teardownCompiler?: boolean;
}

devOutput

类型: boolean
默认值: false

添加于: astro@5.4.0

输出一个基于开发的构建,与在 astro dev 中转换的代码相似。这对于测试仅构建时出现的问题非常有用,同时包含附加的调试信息。

teardownCompiler

类型: boolean
默认值: true

添加于: astro@5.4.0

在构建完成后销毁编译器的 WASM 实例。这可以在单次构建时提升性能,但在连续多次构建时可能导致性能下降。

在同一次执行中构建多个项目时(例如测试期间),禁用这个选项可以显著提升性能并降低峰值内存占用,但代价是持续内存占用会升高。

preview()

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

astro preview 相似,用于启动一个本地服务器来提供你的构建输出。

如果未在配置中设置适配器,则预览服务器将仅服务于构建中静态的文件。如果在配置中设置了适配器,则预览服务器将由适配器提供。适配器不需要提供预览服务器,因此该功能可能不可用,具体取决于你选择的适配器。

import { preview } from "astro";

const previewServer = await preview({
  root: "./my-project",
});

// 如需停止服务器:
await previewServer.stop();

PreviewServer

export interface PreviewServer {
	host?: string;
	port: number;
	closed(): Promise<void>;
	stop(): Promise<void>;
}

host

类型: string

服务器所监听连接的 host。

允许适配器不设置此字段。host 的值通过特殊方式实现。

port

类型: number

服务器所监听连接的端口。

stop()

类型: Promise<void>

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

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

closed()

类型: Promise<void>

返回一个 Promise,该 Promise 将在服务器关闭后结束,如果服务器上发生错误,则拒绝该 Promise。

sync()

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

astro sync 相似,用于为所有的 Astro 模块生成 TypeScript 类型。

import { sync } from "astro";

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

mergeConfig()

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

添加于: astro@5.4.0

astro/config 导入,用于在现有有效的 Astro 配置基础上合并部分配置。

mergeConfig() 接受一个完整的 Astro 配置对象和一个部分配置(任意有效的 Astro 配置选项的集合),返回合并后的有效 Astro 配置。合并规则如下:

  • 数组会被连接(包括集成和 remark 插件)。
  • 对象会递归合并。
  • Vite 选项使用 Vite 自身的 mergeConfig 函数 进行合并,默认启用 isRoot 标志。
  • 可以作为函数提供的选项会被包装成新函数,这些新函数递归合并两个配置的返回值,遵循相同的规则。
  • 其他所有选项会覆盖原有配置。
import { mergeConfig } from "astro/config";

mergeConfig(
  {
    output: 'static',
    site: 'https://example.com',
    integrations: [partytown()],
    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',
	  },
  }
);

// 合并后的结果等价于:
{
  output: 'server',
  site: 'https://example.com',
  base: '/astro',
  integrations: [partytown(), mdx()],
  server: ({command}) => ({
    port: command === 'dev' ? 4321 : 1234,
    host: command === 'dev' ? 'localhost' : 'site.localhost',
  }),
	build: {
		client: './custom-client',
		server: './custom-server',
	},
}

validateConfig()

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

添加于: astro@5.4.0

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

接收以下参数:

  • 待验证的配置
  • 项目根目录
  • 正在执行的 Astro 命令(build, dev, sync 等)

返回的 Promise 会解析为验证后的配置,包含适用于给定 Astro 命令的所有默认值。

import { validateConfig } from "astro/config";

const config = await validateConfig({
  integrations: [partytown()],
}, "./my-project", "build");

// 已应用默认值
await rm(config.outDir, { recursive: true, force: true });
贡献 社区 赞助