Skip to content

CLI 命令

你可以使用 Astro 提供的命令行接口 (CLI) 从终端窗口开发、构建和预览项目。

¥You can use the Command-Line Interface (CLI) provided by Astro to develop, build, and preview your project from a terminal window.

¥astro commands

通过使用你首选的包管理器运行此页面上记录的命令之一来使用 CLI,可选择后跟任何标志。标志定制命令的行为。

¥Use the CLI by running one of the commands documented on this page with your preferred package manager, optionally followed by any flags. Flags customize the behavior of a command.

你最常使用的命令之一是 astro dev。此命令启动开发服务器,并在你工作时在浏览器中提供站点的实时更新预览:

¥One of the commands you’ll use most often is astro dev. This command starts the development server and gives you a live, updating preview of your site in a browser as you work:

Terminal window
# start the development server
npx astro dev

你可以在终端中键入 astro --help 以显示所有可用命令的列表:

¥You can type astro --help in your terminal to display a list of all available commands:

Terminal window
npx astro --help

以下消息将显示在你的终端中:

¥The following message will display in your terminal:

Terminal window
astro [command] [...flags]
Commands
add Add an integration.
build Build your project and write it to disk.
check Check your project for errors.
dev Start the development server.
docs Open documentation in your web browser.
info List info about your current Astro setup.
preview Preview your build locally.
sync Generate TypeScript types for all Astro modules.
preferences Configure user preferences.
telemetry Configure telemetry settings.
Global Flags
--config <path> Specify your config file.
--root <path> Specify your project root folder.
--site <url> Specify your project site.
--base <pathname> Specify your project base.
--verbose Enable verbose logging.
--silent Disable all logging.
--version Show the version number and exit.
--open Open the app in the browser on server start.
--help Show this help message.

¥package.json scripts

你还可以使用 package.json 中的脚本来实现这些命令的较短版本。使用脚本允许你使用你在其他项目(例如 npm run build)中可能熟悉的相同命令。

¥You can also use scripts in package.json for shorter versions of these commands. Using a script allows you to use the same commands that you may be familiar with from other projects, such as npm run build.

当你使用 create astro 向导 创建项目时,会自动为你添加以下最常见 astro 命令(astro devastro buildastro preview)的脚本。

¥The following scripts for the most common astro commands (astro dev, astro build, and astro preview) are added for you automatically when you create a project using the create astro wizard.

当你按照 手动安装 Astro 的说明进行操作时,系统会指示你自行添加这些脚本。你还可以为你经常使用的任何命令手动添加更多脚本到此列表中。

¥When you follow the instructions to install Astro manually, you are instructed to add these scripts yourself. You can also add more scripts to this list manually for any commands you use frequently.

package.json
{
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview"
}
}

你经常会使用这些 astro 命令或运行它们的脚本,而不带任何标志。当你想要自定义命令的行为时,请向命令添加标志。例如,你可能希望在不同的端口上启动开发服务器,或者使用详细日志构建站点以进行调试。

¥You will often use these astro commands, or the scripts that run them, without any flags. Add flags to the command when you want to customize the command’s behavior. For example, you may wish to start the development server on a different port, or build your site with verbose logs for debugging.

Terminal window
# run the dev server on port 8080 using the `start` script in `package.json`
npm run start -- --port 8080
# build your site with verbose logs using the `build` script in `package.json`
npm run build -- --verbose

运行 Astro 的开发服务器。这是一个不打包资源的本地 HTTP 服务器。当你在编辑器中保存更改时,它使用热模块替换 (HMR) 来更新你的浏览器。

¥Runs Astro’s development server. This is a local HTTP server that doesn’t bundle assets. It uses Hot Module Replacement (HMR) to update your browser as you save changes in your editor.

构建你的站点以进行部署。默认情况下,这将生成静态文件并将它们放置在 dist/ 目录中。如果是 SSR 已启用,这将生成为你的站点提供服务所需的服务器文件。

¥Builds your site for deployment. By default, this will generate static files and place them in a dist/ directory. If SSR is enabled, this will generate the necessary server files to serve your site.

可以与下面记录的 通用标志 结合使用。

¥Can be combined with the common flags documented below.

启动本地服务器以提供通过运行 astro build 创建的静态目录(默认为 dist/)的内容。

¥Starts a local server to serve the contents of your static directory (dist/ by default) created by running astro build.

此命令允许你在本地 构建后 预览你的站点,以便在部署之前捕获构建输出中的任何错误。它不是为在生产中运行而设计的。如需生产托管方面的帮助,请查看我们的 部署 Astro 网站 指南。

¥This command allows you to preview your site locally after building to catch any errors in your build output before deploying it. It is not designed to be run in production. For help with production hosting, check out our guide on Deploying an Astro Website.

从 Astro 1.5.0 开始,如果你使用支持它的适配器,astro preview 也适用于 SSR 版本。目前仅 节点适配器 支持 astro preview

¥Since Astro 1.5.0, astro preview also works for SSR builds if you use an adapter that supports it. Currently, only the Node adapter supports astro preview.

可以与下面记录的 通用标志 结合使用。

¥Can be combined with the common flags documented below.

针对你的项目运行诊断(例如 .astro 文件中的类型检查)并向控制台报告错误。如果发现任何错误,该过程将以代码 1 退出。

¥Runs diagnostics (such as type-checking within .astro files) against your project and reports errors to the console. If any errors are found the process will exit with a code of 1.

该命令旨在用于 CI 工作流程。

¥This command is intended to be used in CI workflows.

Flags

使用这些标志来自定义命令的行为。

¥Use these flags to customize the behavior of the command.

该命令将监视项目中的任何更改,并报告任何错误。

¥The command will watch for any changes in your project, and will report any errors.

指定要检查的其他根目录。默认情况下使用当前工作目录。

¥Specifies a different root directory to check. Uses the current working directory by default.

指定要手动使用的 tsconfig.json 文件。如果没有提供,Astro 将尝试查找配置,或自动推断项目的配置。

¥Specifies a tsconfig.json file to use manually. If not provided, Astro will attempt to find a config, or infer the project’s config automatically.

--minimumFailingSeverity <error|warning|hint>

Section titled --minimumFailingSeverity &lt;error|warning|hint&gt;

指定以错误代码退出所需的最低严重性。默认为 error

¥Specifies the minimum severity needed to exit with an error code. Defaults to error.

例如,如果检测到任何警告,运行 astro check --minimumFailingSeverity warning 将导致命令退出并出现错误。

¥For example, running astro check --minimumFailingSeverity warning will cause the command to exit with an error if any warnings are detected.

指定要输出的最低严重性。默认为 hint

¥Specifies the minimum severity to output. Defaults to hint.

例如,运行 astro check --minimumSeverity warning 将显示错误和警告,但不显示提示。

¥For example, running astro check --minimumSeverity warning will show errors and warning, but not hints.

指定在监视模式下不清除检查之间的输出。

¥Specifies not to clear the ouput between checks when in watch mode.

指定在检查项目之前不运行 astro sync

¥Specifies not to run astro sync before checking the project.

Read more about type checking in Astro.

Added in: astro@2.0.0

为所有 Astro 模块生成 TypeScript 类型。这将设置 src/env.d.ts 文件 用于类型推断,并定义依赖于生成类型的功能的模块:

¥Generates TypeScript types for all Astro modules. This sets up a src/env.d.ts file for type inferencing, and defines modules for features that rely on generated types:

将集成添加到你的配置中。阅读 集成指南 中的更多内容。

¥Adds an integration to your configuration. Read more in the integrations guide.

直接从终端启动 Astro Docs 网站。

¥Launches the Astro Docs website directly from the terminal.

报告有关你当前 Astro 环境的有用信息。对于在打开问题时提供信息很有用。

¥Reports useful information about your current Astro environment. Useful for providing information when opening an issue.

Terminal window
astro info

输出示例:

¥Example output:

Astro v3.0.12
Node v20.5.1
System macOS (arm64)
Package Manager pnpm
Output server
Adapter @astrojs/vercel/serverless
Integrations none

使用 astro preferences 命令管理用户首选项。用户首选项特定于各个 Astro 用户,与 astro.config.mjs 文件不同,astro.config.mjs 文件会更改项目中每个人的行为。

¥Manage user preferences with the astro preferences command. User preferences are specific to individual Astro users, unlike the astro.config.mjs file which changes behavior for everyone working on a project.

默认情况下,用户首选项的范围仅限于当前项目,存储在本地 .astro/settings.json 文件中。

¥User preferences are scoped to the current project by default, stored in a local .astro/settings.json file.

使用 --global 标志,用户首选项也可以应用于当前计算机上的每个 Astro 项目。全局用户首选项存储在操作系统特定的位置。

¥Using the --global flag, user preferences can also be applied to every Astro project on the current machine. Global user preferences are stored in an operating system-specific location.

Available preferences

  • devToolbar — 在浏览器中启用或禁用开发工具栏。(默认:true

  • checkUpdates — 启用或禁用 Astro CLI 的自动更新检查。(默认:true

list 命令打印所有可配置用户首选项的当前设置。它还支持机器可读的 --json 输出。

¥The list command prints the current settings of all configurable user preferences. It also supports a machine-readable --json output.

Terminal window
astro preferences list

示例终端输出:

¥Example terminal output:

偏好设置
devToolbar.enabledtrue
checkUpdates.enabledtrue

你可以将 enabledisablereset 首选项设置为其默认值。

¥You can enable, disable, or reset preferences to their default.

例如,要禁用特定 Astro 项目中的 devToolbar:

¥For example, to disable the devToolbar in a specific Astro project:

Terminal window
astro preferences disable devToolbar

要禁用当前计算机上所有 Astro 项目中的 devToolbar:

¥To disable the devToolbar in all Astro projects on the current machine:

Terminal window
astro preferences disable --global devToolbar

稍后可以通过以下方式启用 devToolbar:

¥The devToolbar can later be enabled with:

Terminal window
astro preferences enable devToolbar

reset 命令将首选项重置为其默认值:

¥The reset command resets a preference to its default value:

Terminal window
astro preferences reset devToolbar

为当前 CLI 用户设置遥测配置。遥测是匿名数据,可让 Astro 团队深入了解最常使用的 Astro 功能。欲了解更多信息,请参阅 Astro 的遥测页面

¥Sets telemetry configuration for the current CLI user. Telemetry is anonymous data that provides the Astro team insights into which Astro features are most often used. For more information see Astro’s telemetry page.

可以使用以下 CLI 命令禁用遥测:

¥Telemetry can be disabled with this CLI command:

Terminal window
astro telemetry disable

稍后可以通过以下方式重新启用遥测:

¥Telemetry can later be re-enabled with:

Terminal window
astro telemetry enable

reset 命令重置遥测数据:

¥The reset command resets the telemetry data:

Terminal window
astro telemetry reset

¥Common flags

指定项目根目录的路径。如果未指定,则假定当前工作目录是根目录。

¥Specifies the path to the project root. If not specified, the current working directory is assumed to be the root.

root 用于查找 Astro 配置文件。

¥The root is used for finding the Astro configuration file.

Terminal window
astro --root myRootFolder/myProjectFolder dev

指定相对于项目根目录的配置文件的路径。默认为 astro.config.mjs。如果你对配置文件使用不同的名称或将配置文件放在另一个文件夹中,请使用此选项。

¥Specifies the path to the config file relative to the project root. Defaults to astro.config.mjs. Use this if you use a different name for your configuration file or have your config file in another folder.

Terminal window
astro --config config/astro.config.mjs dev

Added in: astro@3.3.0

为你的项目配置 outDir。传递此标志将覆盖 astro.config.mjs 文件中的 outDir 值(如果存在)。

¥Configures the outDir for your project. Passing this flag will override the outDir value in your astro.config.mjs file, if one exists.

为你的项目配置 site。传递此标志将覆盖 astro.config.mjs 文件中的 site 值(如果存在)。

¥Configures the site for your project. Passing this flag will override the site value in your astro.config.mjs file, if one exists.

Added in: astro@1.4.1

为你的项目配置 base。传递此标志将覆盖 astro.config.mjs 文件中的 base 值(如果存在)。

¥Configures the base for your project. Passing this flag will override the base value in your astro.config.mjs file, if one exists.

指定在哪个端口上运行开发服务器和预览服务器。默认为 4321

¥Specifies which port to run the dev server and preview server on. Defaults to 4321.

--host [optional host address]

Section titled --host [optional host address]

设置开发服务器和预览服务器应监听的网络 IP 地址(即非本地主机 IP)。这对于在开发过程中在本地设备(例如手机)上测试你的项目非常有用。

¥Sets which network IP addresses the dev server and preview server should listen on (i.e. non-localhost IPs). This can be useful for testing your project on local devices like a mobile phone during development.

  • --host — 监听所有地址,包括 LAN 和公共地址

  • --host <custom-address> — 在 <custom-address> 上公开网络 IP 地址

启用详细日志记录,这在调试问题时很有帮助。

¥Enables verbose logging, which is helpful when debugging an issue.

启用静默日志记录,这将在没有任何控制台输出的情况下运行服务器。

¥Enables silent logging, which will run the server without any console output.

¥Global flags

使用这些标志获取有关 astro CLI 的信息。

¥Use these flags to get information about the astro CLI.

打印 Astro 版本号并退出。

¥Prints the Astro version number and exits.

服务器启动时自动在浏览器中打开应用。可以传递完整的 URL 字符串(例如 --open http://example.com)或路径名(例如 --open /about)来指定要打开的 URL。

¥Automatically opens the app in the browser on server start. Can be passed a full URL string (e.g. --open http://example.com) or a pathname (e.g. --open /about) to specify the URL to open.

打印帮助消息并退出。

¥Prints the help message and exits.

¥Advanced APIs (Experimental)

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

¥If you need more control when running Astro, the "astro" package also 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?: "development" | "production";
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.

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

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

构建站点时用于生成 “development” 或 “production” 代码的模式。

¥The mode used when building your site to generate either “development” or “production” code.

类型:"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>;
}

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

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

原始 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 的开发服务器 公开的 Chokidar 文件监视器

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

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

¥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) => Promise<void>

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

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

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

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

类型:(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>;
}

服务器监听连接的主机。

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

服务器监听连接的端口。

¥The port where the server is listening for connections.

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

¥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,它会在服务器关闭后解析,如果服务器上发生错误则会拒绝。

¥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",
});

使用 Astro Studio 进行身份验证。这是运行所有数据库管理命令(包括 astro link)所必需的。

¥Authenticate with Astro Studio. This is required to run all database management commands, including astro link.

链接到你的 Studio 托管数据库。这是运行 Astro DB 命令 进行数据库管理所必需的。要链接数据库,系统将提示你选择现有数据库或创建新数据库。

¥Link to your Studio hosted database. This is required to run Astro DB commands for database management. To link a database, you will be prompted to select an existing database or create a new one.

退出 Astro Studio 并删除任何本地存储的身份验证密钥。

¥Log out of Astro Studio and remove any locally stored authentication keys.

Astro 中文网 - 粤ICP备13048890号