# 命令行接口

> Source: https://strapi.nodejs.cn/cms/cli

🌐 Command Line Interface (CLI)

Strapi 带有功能齐全的命令行接口（CLI），使你可以在几秒钟内搭建和管理项目。CLI 可与 `yarn` 和 `npm` 包管理器一起使用。

🌐 Strapi comes with a full featured Command Line Interface (CLI) which lets you scaffold and manage your project in seconds. The CLI works with both the `yarn` and `npm` package managers.

本页上的 Strapi CLI 命令按类别分组：

🌐 Strapi CLI commands on the present page are grouped by category:

| 类别 | 命令 |
|---|---|
| [开发](#development) | `develop`, `start`, `build`, `console` |
| [云](#cloud) | `login`, `link`, `deploy`, `logout` |
| [数据管理](#data-management) | `export`, `import`, `transfer` |
| [项目信息](#project-information) | `report`, `telemetry:disable`, `telemetry:enable`, `version`, `help` |
| [配置](#configuration) | `configuration:dump`, `configuration:restore` |
| [管理](#administration) | `admin:create-user`, `admin:reset-user-password`, `admin:list-users`, `admin:active-user`, `admin:block-user`, `admin:delete-user` |
| [代码生成](#code-generation) | `generate`, `openapi generate`, `templates:generate`, `ts:generate-types` |
| [列表](#listing) | `routes:list`, `policies:list`, `middlewares:list`, `content-types:list`, `hooks:list`, `controllers:list`, `services:list` |

:::caution

像 `strapi admin:create-user` 这样的交互命令在使用 `npm` 时不会显示提示。请考虑使用 `yarn` 包管理器。

🌐 Interactive commands such as `strapi admin:create-user` don't display prompts with `npm`. Please consider using the `yarn` package manager.

:::

## 一般考虑 {#general-considerations}

🌐 General considerations

建议仅在本地安装 Strapi，这需要在所有以下 `strapi` 命令前加上用于项目设置的包管理器（例如 `npm run strapi help` 或 `yarn strapi help`）或专用的 node 包执行器（例如 `npx strapi help`）。

🌐 It is recommended to install Strapi locally only, which requires prefixing all of the following `strapi` commands with the package manager used for the project setup (e.g `npm run strapi help` or `yarn strapi help`) or a dedicated node package executor (e.g. `npx strapi help`).

:::note The format for passing options differs between npm and yarn

* 要使用 `npm` 传递选项，请使用以下语法：<br/>   `npm run strapi <command> -- --<option>`。
* 要使用 `yarn` 传递选项，请使用以下语法：<br/>   `yarn strapi <command> --<option>`

:::

<details>
<summary>ℹ️ Strapi v4 CLI 命令已从 Strapi 5 中移除：</summary>

Strapi v4 的 `strapi install`、`strapi uninstall`、`strapi new` 和 `strapi watch-admin` 命令在 Strapi 5 中已被移除：

🌐 The `strapi install`, `strapi uninstall`, `strapi new`, and `strapi watch-admin` commands from Strapi v4 have been removed in Strapi 5:

| Strapi v4 命令 | Strapi 5 对应命令 |
| --- | --- |
| `strapi install [plugin]` | 使用对应插件的 npx 命令（可在市场中找到，见 [Marketplace](/cms/plugins/installing-plugins-via-marketplace)） |
| `strapi new` | 使用相应的 yarn 或 npx 命令来创建新的 Strapi 项目（见 [CLI 安装指南](/cms/installation/cli)） |
| `strapi watch-admin` | `yarn develop` 或 `npm run develop` 总是在“watch-admin”模式下启动 Strapi 服务器。要在 Strapi 5 中禁用此功能，请运行 `yarn develop --no-watch-admin` 或 `npm run develop --no-watch-admin`。 |

</details>

## 新项目的安全默认设置 {#security-defaults-for-new-projects}

🌐 Security defaults for new projects

使用 `create-strapi-app` 搭建的项目在生成的 `config/` 文件和 `.env` 中包含预配置的安全加固默认设置：

🌐 Projects scaffolded with `create-strapi-app` include security-hardened defaults pre-configured in the generated `config/` files and `.env`:

| 默认 | 配置位置 | 目的 |
|---|---|---|
| `rest.strictParams: true` 和 `documents.strictParams: true` | `config/api.*` | 拒绝带有未知查询或正文参数的请求（请参见 [API 配置](/cms/configurations/api)）。 |
| `jwtManagement: 'refresh'` 与 `sessions.httpOnly: true` | `config/plugins.*`（用户-权限） | 启用基于刷新令牌的身份验证，使用 HTTP-only 会话 Cookie，用于用户与权限功能（参见 [用户与权限](/cms/features/users-permissions#jwt-management-modes)）。 |
| `upload.config.security.allowedTypes` 和 `upload.config.security.deniedTypes` | `config/plugins.*`（上传） | 限制上传到批准的文件类型并阻止危险的扩展名（参见 [媒体库](/cms/features/media-library#available-options)）。 |
| `webhooks.populateRelations: false` | `config/server.*` | 防止关系数据包含在 webhook 有效负载中（参见[服务器配置](/cms/configurations/server)）。 |
| `JWT_SECRET` | `.env` | 随机生成的秘密包含在脚手架的 `.env` 文件中。 |

所有默认设置都可以在相应的配置文件中进行调整，以符合你项目的需求。

🌐 All defaults can be adjusted in the corresponding configuration files to match your project's requirements.

## 发展 {#development}

🌐 Development

这些命令在开发过程中启动并构建你的 Strapi 应用。

🌐 These commands start and build your Strapi application during development.

### `strapi develop`

**别名**: `dev`

启动一个启用自动重新加载的 Strapi 应用。

🌐 Start a Strapi application with auto-reloading enabled.

Strapi 在运行时会修改/创建文件，并且在创建新文件时需要重启。为实现这一点，`strapi develop` 添加了一个文件监视器，并在必要时重启应用。

🌐 Strapi modifies/creates files at runtime and needs to restart when new files are created. To achieve this, `strapi develop` adds a file watcher and restarts the application when necessary.

Strapi 还添加了中间件来支持管理面板的 HMR（热模块替换）。这使你可以在无需重启应用或运行单独服务器的情况下自定义管理面板。

🌐 Strapi also adds middlewares to support HMR (Hot Module Replacement) for the administration panel. This allows you to customize the administration panel without having to restart the application or run a separate server.

```shell
strapi develop
options: [--bundler | --open | --no-watch-admin | --no-build-admin | --polling | --debug | --silent]
```

- **strapi develop --bundler [bundler]**<br/>  选择用于管理面板构建的打包器（`vite` 或 `webpack`）。
- **strapi develop --open**<br/>  启动你的应用并启用自动重载，同时用默认浏览器打开正在运行的管理面板。
- **strapi develop --no-watch-admin**<br/>  当对管理员面板代码进行更改时，防止服务器自动重载。
- **strapi develop --no-build-admin**<br/>  当启用 `--no-watch-admin` 时，防止构建管理员面板。
- **strapi develop --polling**<br/>  监视网络目录中的文件更改。
- **strapi develop --debug**<br/>  启用带有详细日志的调试模式。
- **strapi develop --silent**<br/>  抑制日志。
- **strapi develop --install-deps**<br/>  自动安装缺失的管理员同伴依赖 (`react`, `react-dom`, `react-router-dom`, `styled-components`)。此功能默认启用。
- **strapi develop --no-install-deps**<br/>  跳过自动安装缺失的管理员同级依赖，如果有任何缺失将立即失败。

:::warning

你永远不应该使用此命令在生产环境中运行 Strapi 应用。

🌐 You should never use this command to run a Strapi application in production.

:::

### `strapi start`

启动一个禁用自动重新加载的 Strapi 应用。

🌐 Start a Strapi application with auto-reloading disabled.

此命令用于在不重启和不写入文件的情况下运行 Strapi 应用，主要用于生产环境。
某些功能，例如内容类型构建器，在 `strapi start` 模式下被禁用，因为它们需要应用重启。`start` 命令可以通过在前面添加 [环境变量](/cms/configurations/environment#strapi) 来自定义应用启动。

🌐 This command is to run a Strapi application without restarts and file writes, primarily for use in production.
Certain features such as the Content-type Builder are disabled in the `strapi start` mode because they require application restarts. The `start` command can be prefaced with [environment variables](/cms/configurations/environment#strapi) to customize the application start.

### `strapi build`

构建你的管理员面板。

🌐 Builds your admin panel.

```bash
strapi build
```

| 选项 | 类型 | 描述 |
| --- | :--: | --- |
| `-d, --debug` | - | 启用带详细日志的调试模式（默认：false） |
| `--minify` | - | 压缩输出（默认：true） |
| `--no-optimization` | - | [已弃用]：请改用压缩功能 |
| `--silent` | - | 不记录任何日志（默认：false） |
| `--sourcemaps` | - | 生成 source map（默认：false） |
| `--stats` | - | 将构建统计输出到控制台（默认：false） |
| `--install-deps` | - | 自动安装缺失的管理员依赖（默认：false） |
| `--no-install-deps` | - | 跳过自动安装，如果依赖缺失则失败（默认：true） |

### `strapi console`

启动服务器并实时执行应用中的命令。

🌐 Start the server and evaluate commands in your application in real time.

```bash
strapi console
```

`console` 命令会编译并加载你的应用，在后台启动服务器，然后打开一个 Node.js [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)。REPL 提供基于你应用名称的提示符，并通过全局 `strapi` 对象访问所有 Strapi API。通过连续按 `Ctrl-C` 两次关闭 REPL 可以优雅地停止服务器。

#### 可用的助手 {#available-helpers}

🌐 Available helpers

`strapi` 对象提供以下 getter 和方法来与你的应用进行交互：

🌐 The `strapi` object exposes the following getters and methods to interact with your application:

- `strapi.services` 和 `strapi.service(uid)` 使用 [服务](/cms/backend-customization/services)
- `strapi.controllers` 和 `strapi.controller(uid)` 调用 [控制器](/cms/backend-customization/controllers)
- `strapi.contentTypes` 和 `strapi.contentType(uid)` 检查 [内容类型](/cms/backend-customization/models)
- `strapi.components` 列出组件
- `strapi.policies` 和 `strapi.policy(name)` 用于 [政策](/cms/backend-customization/policies)
- `strapi.middlewares` 和 `strapi.middleware(name)` 用于 [中间件](/cms/backend-customization/middlewares)
- `strapi.plugins` 和 `strapi.plugin(name)` 用于插件
- `strapi.hooks` 和 `strapi.hook(name)` 用于钩子
- `strapi.apis` 和 `strapi.api(name)` 用于 API
- `strapi.db` 通过 [查询引擎 API](/cms/api/query-engine) 直接查询数据库，例如如下所示：<br/><br/>

  ```js
  await strapi.db.query('api::article.article').findMany();
  ```

使用此环境测试代码并检查你的项目，并直接访问所有 Strapi API。

🌐 Use this environment to test code and inspect your project with direct access to all Strapi APIs.

:::note

Strapi 使用 Node.js 的一个名为  [AsyncLocalStorage](https://nodejs.cn/api/async_context.html)  的功能来使上下文在任何地方都可用。

:::

## 云 {#cloud}

🌐 Cloud

这些命令与 Strapi Cloud 交互。有关详细信息，请参阅 [Cloud CLI](/cloud/cli/cloud-cli) 文档。

🌐 These commands interact with Strapi Cloud. See the [Cloud CLI](/cloud/cli/cloud-cli) documentation for details.

### `strapi login`

登录到 Strapi Cloud（请参阅 [Cloud CLI](/cloud/cli/cloud-cli#strapi-login) 文档）。

🌐 Logs in to Strapi Cloud (see [Cloud CLI](/cloud/cli/cloud-cli#strapi-login) documentation).

### `strapi link`

将本地项目链接到现有的 Strapi Cloud 项目（参见 [Cloud CLI](/cloud/cli/cloud-cli#strapi-link) 文档）。

🌐 Links the local project to an existing Strapi Cloud project (see [Cloud CLI](/cloud/cli/cloud-cli#strapi-link) documentation).

### `strapi deploy`

将关联的本地项目部署到 Strapi 云（参见 [Cloud CLI](/cloud/cli/cloud-cli#strapi-deploy) 文档）。

🌐 Deploys a linked local project to Strapi Cloud (see [Cloud CLI](/cloud/cli/cloud-cli#strapi-deploy) documentation).

### `strapi logout`

从 Strapi Cloud 登出（参见 [Cloud CLI](/cloud/cli/cloud-cli#strapi-logout) 文档）。

🌐 Logs out from Strapi Cloud (see [Cloud CLI](/cloud/cli/cloud-cli#strapi-logout) documentation).

## 数据管理 {#data-management}

🌐 Data management

这些命令用于在 Strapi 实例之间导出、导入和传输数据。

🌐 These commands export, import, and transfer data between Strapi instances.

### `strapi export`

[导出你的项目数据](/cms/features/data-management)。默认设置会创建一个 `.tar` 文件，使用 `gzip` 压缩并使用 `aes-128-ecb` 加密。

```bash
strapi export
```

该归档包含如 `configuration`、`entities`、`links` 和 `schemas` 的文件夹，数据存储在  [JSON lines](https://jsonlines.org/)  文件中。使用 `--no-encrypt --no-compress` 生成可读取的 `.tar`，可以进行检查或转换为其他格式。

导出的文件会自动使用格式 `export_YYYYMMDDHHMMSS`，并带有当前日期和时间戳进行命名。或者，你可以使用 `-f` 或 `--file` 标志来指定文件名。下表提供了所有可用的命令行标志选项：

🌐 The exported file is automatically named using the format `export_YYYYMMDDHHMMSS` with the current date and timestamp. Alternately, you can specify the filename using the `-f` or `--file` flag. The following table provides all of the available options as command line flags:

| 选项 | 类型 | 描述 |
| --- | :----: | --- |
| `--no-encrypt` | - | 禁用文件加密，并禁用 `key` 选项。 |
| `--no-compress` | - | 禁用文件压缩。 |
| `-k`, <br/>`--key` | 字符串 | 通过 `export` 命令传递加密密钥。 <br/> `--key` 选项不能与 `--no-encrypt` 组合使用。 |
| `-f`, <br/>`--file` | 字符串 | 指定导出文件名（tar）或输出目录路径（dir）。tar 导出不要包括文件扩展名。 |
| `--format` | 字符串 | 导出格式：`tar`（默认）或 `dir`。目录导出需要 `--no-encrypt`。 |
| `--exclude` | 字符串 | 使用逗号分隔的数据类型排除数据。可用类型有：`content`、`files` 和 `config`。 |
| `--only` | 字符串 | 仅包含这些数据。可用类型有：`content`、`files` 和 `config`。 |
| `-h`, <br/>`--help` | - | 显示 `strapi export` 命令的帮助信息。 |

**示例**

使用自定义文件名导出数据（`myData.tar.gz.enc`）：

🌐 Export data with a custom filename (`myData.tar.gz.enc`):

```bash
strapi export -f myData
```

导出数据而不加密：

🌐 Export data without encryption:

```bash
strapi export --no-encrypt
```

将数据导出为未打包的目录：

🌐 Export data as an unpacked directory:

```bash
strapi export --format dir --no-encrypt -f my-export
```

### `strapi import`

[将数据导入](/cms/features/data-management)到你的项目中。导入的数据必须来自另一个 Strapi 应用。你必须传递 `--file` 选项以指定导入操作的文件或目录。

```bash
strapi import
```

该命令接受由 `strapi export`（`.tar`、`.tar.gz`、`.tar.gz.enc`）生成的归档文件以及已解压的导出目录。对于归档导入，压缩和加密会从文件名中检测。当 `-f` 指向一个目录时，压缩和加密将自动跳过。

🌐 The command accepts archives generated by `strapi export` (`.tar`, `.tar.gz`, `.tar.gz.enc`) and unpacked export directories. Compression and encryption are detected from the filename for archive imports. When `-f` points to a directory, encryption and compression are skipped automatically.

| 选项 | 类型 | 描述 |
| --- | --- | --- |
| `-k,` `--key` | 字符串 | 在命令中提供加密密钥，而不是在随后提示时输入。 |
| `-f`, `--file` | 字符串 | 指向 `.tar[.gz][.enc]` 存档文件的路径或解压后的导出目录。 |
| `-h`, `--help` | - | 显示 `strapi import` 帮助命令。 |

**示例**

导入数据并传递加密密钥：

🌐 Import data and pass an encryption key:

```bash
strapi import -f your-filepath-and-filename --key my-key
```

从未打包的导出目录导入：

🌐 Import from an unpacked export directory:

```bash
strapi import -f ./my-export
```

### `strapi transfer`

[在两个 Strapi 实例之间传输数据](/cms/data-management/transfer)。此命令主要用于本地实例与远程实例之间或两个远程实例之间。`transfer` 命令需要一个传输令牌，该令牌可在目标实例的管理面板中生成。有关创建传输令牌的详细文档，请参阅[用户指南](/cms/features/data-management#admin-panel-settings)。

:::caution

目标 Strapi 实例应该使用 `start` 命令运行，而不是 `develop` 命令。

🌐 The destination Strapi instance should be running with the `start` command and not the `develop` command.

:::

| 选项 | 描述 |
| --- | --- |
| `--to [destinationURL]` | 目标 Strapi 实例上 `/admin` 端点的完整 URL<br />（例如: `--to https://my-beautiful-strapi-website/admin`） |
| `--to-token [transferToken]` | 远程 Strapi 目标的传输令牌 |
| `--from [sourceURL]` | 远程 Strapi 实例的 `/admin` 端点的完整 URL，用于拉取数据<br />（例如: `--from https://my-beautiful-strapi-website/admin`） |
| `‑‑from‑token` | 来自 Strapi 源实例的传输令牌 |
| `--force` | 对所有提示自动回答“是”，包括可能破坏性的请求，并非交互式运行 |
| `--exclude` | 使用逗号分隔的数据类型排除数据。可用类型包括: `content`、`files` 和 `config` |
| `--only` | 仅包含这些数据。可用类型包括: `content`、`files` 和 `config` |
| `-h`、`--help` | 显示 `strapi transfer` 的命令 |

:::caution

需要 `--to` 或 `--from`，但目前不允许同时输入两者或两者都不输入。

🌐 Either `--to` or `--from` is required, but it's not currently allowed to enter both or neither.

:::

**示例**

```bash
strapi transfer --to http://example.com/admin --to-token my-transfer-token
```

## 项目信息 {#project-information}

🌐 Project information

这些命令用于显示项目详情、管理遥测，并显示已安装的版本。

🌐 These commands display project details, manage telemetry, and show the installed version.

### `strapi report`

打印出对调试有用且报告问题时所需的调试信息。

🌐 Prints out debug information useful for debugging and required when reporting an issue.

| 选项 | 描述 |
| --- | --- |
| `-u`，`--uuid` | 包含项目 UUID |
| `-d`，`--dependencies` | 包含项目依赖 |
| `--all` | 记录所有数据 |

**示例**

要在输出中包含项目 UUID 和依赖：

🌐 To include the project UUID and dependencies in the output:

```bash
strapi report --uuid --dependencies
```

要记录所有内容，请使用 `--all` 选项：

🌐 To log everything, use the `--all` option:

```bash
strapi report --all
```

### `strapi telemetry:disable`

禁用该项目的数据收集（请参阅 [使用信息](/cms/usage-information)）。

🌐 Disable data collection for the project (see [Usage Information](/cms/usage-information)).

```bash
strapi telemetry:disable
```

### `strapi telemetry:enable`

在项目被禁用后重新启用数据收集（见[使用信息](/cms/usage-information)）。

🌐 Re-enable data collection for the project after it was disabled (see [Usage Information](/cms/usage-information)).

```bash
strapi telemetry:enable
```

### `strapi version`

打印当前安装的 Strapi 版本。 如果该命令是全局安装的 Strapi，则会输出当前全局安装的版本；如果从包含 Strapi 项目的指定文件夹运行该命令，则会输出该 Strapi 项目中的当前版本。

🌐 Print the currently installed Strapi version.
It will output the current globally installed version if this command is strapi is installed globally, or the current version of Strapi within a Strapi project if the command is run from a given folder containing a Strapi project.

```bash
strapi version
```

### `strapi help`

列出 CLI 命令。

🌐 List CLI commands.

```bash
strapi help
```

## 配置 {#configuration}

🌐 Configuration

这些命令用于导出和恢复应用存储的配置。

🌐 These commands dump and restore your application's stored configuration.

### `strapi configuration:dump`

**别名**: `config:dump`

将配置转储到文件或标准输出以帮助你迁移到生产环境。

🌐 Dumps configurations to a file or stdout to help you migrate to production.

转储格式将是 JSON 数组。

🌐 The dump format will be a JSON array.

```bash title="strapi configuration:dump"

Options:
  -f, --file <file>  Output file, default output is stdout
  -p, --pretty       Format the output JSON with indentation and line breaks (default: false)
```

**示例**

- `strapi configuration:dump -f dump.json`
- `strapi config:dump --file dump.json`
- `strapi config:dump > dump.json`

所有这些例子都是等价的。

🌐 All these examples are equivalent.

:::caution

在配置你的应用时，你通常需要输入第三方服务（例如身份验证提供者）的凭据。请注意，这些凭据也会被输出到此命令的输出中。如果有疑问，你应避免将转储文件提交到版本控制系统中。以下是一些你可以探索的方法：

🌐 When configuring your application you often enter credentials for third party services (e.g authentication providers). Be aware that those credentials will also be dumped into the output of this command.
In case of doubt, you should avoid committing the dump file into a versioning system. Here are some methods you can explore:

- 将文件直接复制到所需的环境并在那里运行恢复命令。
- 将文件放在安全位置，并在部署时使用正确的凭据下载它。
- 在提交之前对文件进行加密，并在运行恢复命令时对其进行解密。

:::

### `strapi configuration:restore`

**别名**: `config:restore`

将配置转储恢复到你的应用中。

🌐 Restores a configuration dump into your application.

输入格式必须是 JSON 数组。

🌐 The input format must be a JSON array.

```bash
strapi configuration:restore

Options:
  -f, --file <file>          Input file, default input is stdin
  -s, --strategy <strategy>  Strategy name, one of: "replace", "merge", "keep". Defaults to: "replace"
```

**示例**

- `strapi configuration:restore -f dump.json`
- `strapi config:restore --file dump.json -s replace`
- `cat dump.json | strapi config:restore`
- `strapi config:restore < dump.json`

所有这些例子都是等价的。

🌐 All these examples are equivalent.

**策略**

运行恢复命令时，你可以选择三种不同的策略：

🌐 When running the restore command, you can choose from three different strategies:

- **替换**：将创建缺失的键并替换现有的键。
- **合并**：将创建缺失的键，并将现有键与其新值合并。
- **保留**：将创建缺失的键，并保持现有键不变。

## 管理 {#administration}

🌐 Administration

这些命令用于管理 Strapi 管理面板的管理员账户。

🌐 These commands manage administrator accounts for the Strapi admin panel.

### `strapi admin:create-user`

**别名** `admin:create`

创建一个管理员。管理员的名字、姓氏、电子邮件和密码可以是：

🌐 Creates an administrator.
Administrator's first name, last name, email, and password can be:

- 作为选项传递
- 或者如果你调用命令而不传递任何选项，则以交互方式设置。

**示例**

```bash

strapi admin:create-user --firstname=Kai --lastname=Doe --email=chef@strapi.io --password=Gourmet1234
```

**选项**

| 选项 | 类型 | 描述 | 是否必填 |
| --- | --- | --- | --- |
| -f, --firstname | 字符串 | 管理员的名字 | 是 |
| -l, --lastname | 字符串 | 管理员的姓氏 | 否 |
| -e, --email | 字符串 | 管理员的电子邮件 | 是 |
| -p, --password | 字符串 | 管理员的新密码 | 否 |
| -h, --help | | 显示命令帮助 | 否 |

### `strapi admin:reset-user-password`

**别名** `admin:reset-password`

重置管理员用户的密码。
你可以将电子邮件和新密码作为选项传递，或者如果在不传递选项的情况下调用命令，则可以交互式设置它们。

🌐 Reset an admin user's password.
You can pass the email and new password as options or set them interactively if you call the command without passing the options.

**示例**

```bash

strapi admin:reset-user-password --email=chef@strapi.io --password=Gourmet1234
```

**选项**

| 选项 | 类型 | 描述 |
| --- | --- | --- |
| -e, --email | 字符串 | 用户邮箱 |
| -p, --password | 字符串 | 用户的新密码 |
| -h, --help | | 显示命令帮助 |

### `strapi admin:list-users`

**别名** `admin:list`

显示一个表格，列出所有管理员账户，包括他们的ID、电子邮件、名字和姓氏、活跃状态、被阻止状态以及分配的角色。

🌐 Displays a table listing all administrator accounts, including their ID, email, first and last name, active status, blocked status, and assigned roles.

```bash
strapi admin:list-users
```

### `strapi admin:active-user`

**别名** `admin:active`

设置管理员账户的活动状态。电子邮件和活动状态可以作为选项传递，或者如果在没有选项的情况下调用命令，也可以交互式提供。

🌐 Sets the active status of an administrator account. The email and active status can be passed as options or provided interactively if you call the command without options.

**示例**

```bash
strapi admin:active-user --email=chef@strapi.io --active=true
```

**选项**

| 选项 | 类型 | 描述 | 必填 |
| --- | --- | --- | --- |
| -e, --email | 字符串 | 管理员的电子邮件 | 是 |
| -a, --active | 字符串 | 要设置的激活状态（`true` 或 `false`） | 是 |
| -h, --help | | 显示命令帮助 | 否 |

### `strapi admin:block-user`

**别名** `admin:block`

设置管理员账户的阻止状态。电子邮件和阻止状态可以作为选项传递，或者如果在不使用选项的情况下调用命令，则可以交互式提供。

🌐 Sets the blocked status of an administrator account. The email and block status can be passed as options or provided interactively if you call the command without options.

**示例**

```bash
strapi admin:block-user --email=chef@strapi.io --block=true
```

**选项**

| 选项 | 类型 | 描述 | 必填 |
| --- | --- | --- | --- |
| -e, --email | 字符串 | 管理员的电子邮件 | 是 |
| -b, --block | 字符串 | 要设置的阻止状态（`true` 或 `false`） | 是 |
| -h, --help | | 显示命令帮助 | 否 |

### `strapi admin:delete-user`

**别名** `admin:delete`

删除一个现有的管理员账户。电子邮件可以作为选项传递，或者如果在没有选项的情况下调用命令，可以交互式提供。在删除之前会显示交互式确认提示。

🌐 Deletes an existing administrator account. The email can be passed as an option or provided interactively if you call the command without options. An interactive confirmation prompt is shown before deletion.

**示例**

```bash
strapi admin:delete-user --email=chef@strapi.io
```

**选项**

| 选项 | 类型 | 描述 | 必填 |
| --- | --- | --- | --- |
| -e, --email | 字符串 | 管理员的电子邮件 | 是 |
| -h, --help |  | 显示命令帮助 | 否 |

## 代码生成 {#code-generation}

🌐 Code generation

这些命令用于搭建 API、内容类型和其他项目文件。

🌐 These commands scaffold APIs, content-types, and other project files.

### `strapi generate`

生成 APIs、[控制器](/cms/backend-customization/controllers)、[内容类型](/cms/backend-customization/models)、[策略](/cms/backend-customization/policies)、[中间件](/cms/backend-customization/middlewares)、[服务](/cms/backend-customization/services) 和 [迁移](/cms/database-migrations)。

🌐 Generate APIs, [controllers](/cms/backend-customization/controllers), [content-types](/cms/backend-customization/models), [policies](/cms/backend-customization/policies), [middlewares](/cms/backend-customization/middlewares), [services](/cms/backend-customization/services), and [migrations](/cms/database-migrations).

```bash
strapi generate
```

该命令显示一个交互式菜单，其中包含以下选项：

🌐 The command displays an interactive menu with the following options:

- **api** - 生成一个带有控制器和服务的新 API
- **控制器** - 生成一个新的控制器
- **内容类型** - 使用模式生成新的内容类型
- **政策** - 生成一项新政策
- **中间件** - 生成一个新的中间件
- **迁移** - 生成一个新的数据库迁移
- **服务** - 生成一个新的服务

![strapi generate GIF](/img/assets/cli/strapi-generate.gif)

生成器会自动检测 TypeScript 或 JavaScript，并创建带有正确扩展名的文件（`.ts` 或 `.js`）。
生成的文件包含带注释的示例。单数和复数名称必须不同，并使用 **kebab-case 格式** 。

<ExpandableContent maxHeight="120px" showMoreText="Show more…" showLessText="Show less">

#### API生成器 {#api-generator}

🌐 API generator

创建一个带有 [controller](/cms/backend-customization/controllers) 和 [service](/cms/backend-customization/services) 文件的 API。

🌐 Creates an API with [controller](/cms/backend-customization/controllers) and [service](/cms/backend-customization/services) files.

**生成的文件：** `controllers/[name].js|ts`、`services/[name].js|ts` 和 `routes/[name].js|ts`（仅标准 API）

#### 内容类型生成器 {#content-type-generator}

🌐 Content-type generator

创建一个包含可选 API 文件的内容类型架构。

🌐 Creates a content type schema with optional API files.

##### 可用属性类型 {#available-attribute-types}

🌐 Available attribute types

| 类型 | 描述 |
| --- | --- |
| `string` | 短文本 |
| `text` | 长文本 |
| `richtext` | 富文本编辑器 |
| `email` | 电子邮件字段 |
| `password` | 密码字段 |
| `integer` | 整数 |
| `biginteger` | 大整数 |
| `float` | 小数 |
| `decimal` | 精确小数 |
| `date` | 仅日期 |
| `time` | 仅时间 |
| `datetime` | 日期和时间 |
| `timestamp` | Unix 时间戳 |
| `boolean` | 真/假 |
| `json` | JSON 数据 |
| `enumeration` | 预定义值 |
| `media` | 文件上传 |

##### 生成的文件 {#generated-files}

🌐 Generated files

| 条件 | 生成的文件 |
| --- | --- |
| 仅内容类型 | `content-types/[name]/schema.json` |
| 带 API 引导 | <ul><li>`content-types/[name]/schema.json`</li><li>`controllers/[name].js\|ts`</li><li>`services/[name].js\|ts`</li><li>`routes/[name].js\|ts`</li></ul> |

#### 控制器生成器 {#controller-generator}

🌐 Controller generator

创建一个带有基本操作结构的 [controller](/cms/backend-customization/controllers) 文件。

🌐 Creates a [controller](/cms/backend-customization/controllers) file with basic action structure.

**生成的文件:** `controllers/[name].js|ts`

#### 服务生成器 {#service-generator}

🌐 Service generator

创建一个具有基本结构的[服务](/cms/backend-customization/services)文件。

🌐 Creates a [service](/cms/backend-customization/services) file with basic structure.

**生成的文件:** `services/[name].js|ts`

#### 政策生成器 {#policy-generator}

🌐 Policy generator

创建一个用于访问控制的[策略](/cms/backend-customization/policies)文件。

🌐 Creates a [policy](/cms/backend-customization/policies) file for access control.

**生成的文件:** `policies/[name].js|ts`

#### 中间件生成器 {#middleware-generator}

🌐 Middleware generator

为请求处理创建一个 [middleware](/cms/backend-customization/middlewares) 文件。

🌐 Creates a [middleware](/cms/backend-customization/middlewares) file for request processing.

**生成的文件:** `middlewares/[name].js|ts`

#### 迁移生成器 {#migration-generator}

🌐 Migration generator

创建一个带时间戳的[migration](/cms/database-migrations)文件。

🌐 Creates a timestamped [migration](/cms/database-migrations) file.

**生成的文件:** `database/migrations/[timestamp].[name].js|ts`

#### 配置选项 {#configuration-options}

🌐 Configuration options

`strapi generate` 交互式命令行接口可能根据所选择生成的 Strapi 元素提供各种配置选项：

🌐 The `strapi generate` interactive CLI may offer various configuration options depending on the chosen Strapi element to generate:

##### 目的地选择 {#destination-choices}

🌐 Destination choices

创建内容类型、控制器、策略、中间件或服务时，你可以选择其目标：

🌐 When creating a content-type, controller, policy, middleware, or service, you can choose its destination:

| 选项 | 描述 |
| --- | --- |
| **新建 API** | 创建一个新的 API 文件夹 |
| **现有 API** | 添加到现有的 API 文件夹 |
| **现有插件** | 添加到现有的插件文件夹 |
| **根目录** | 添加到项目根目录（仅限策略和中间件） |

##### 特定内容类型的选项 {#content-type-specific-options}

🌐 Content-type specific options

在创建内容类型时，你可以选择创建集合类型或单一类型（有关差异，请参见 [内容类型构建器](/cms/features/content-type-builder) 文档）：

🌐 When creating a content-type, you can choose to create a collection type or a single type (see [Content-Type Builder](/cms/features/content-type-builder) documentation for differences):

| 类型 | 描述 | 示例 |
| --- | --- | --- |
| **集合类型** | 用于多个条目 | 文章，用户 |
| **单一类型** | 用于单个条目 | 首页，设置 |

你还需要定义各种类型的名称。下表解释了它们的区别。只有显示名称需要手动定义，你可以按回车键接受单数和复数名称的默认建议名称。单数和复数名称对于 API 端点很重要（详情请参阅 [REST API](/cms/api/rest#endpoints) 文档）：

🌐 You will also have to define various types of names. The following table explains their differences. Only the display name needs to be manually defined, and you can press Enter to accept the default suggested name for the singular and plural names. Singular and plural names matter for API endpoints (see [REST API](/cms/api/rest#endpoints) documentation for details):

| 字段 | 格式 | 描述 | 示例 |
| --- | --- | --- | --- |
| **显示名称** | 可读 | 在管理面板中显示的名称 | 博客文章 |
| **单数名称** | Kebab-case | 用于 API 端点 | blog-post |
| **复数名称** | Kebab-case | 用于集合 | blog-posts |

### `strapi openapi generate`

为你的 Strapi 应用生成 [OpenAPI 规范](/cms/api/openapi)。

```bash
strapi openapi generate
```

| 选项 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| `--output` | `string` | `./openapi-spec.json` | 生成的规范文件的输出路径 |

#### 例子 {#examples}

🌐 Examples

```bash
# Generate OpenAPI specification (default)
yarn strapi openapi generate

# Generate with custom output path
yarn strapi openapi generate --output ./docs/api-spec.json
```
```bash
# Generate OpenAPI specification (default)
npm run strapi openapi generate

# Generate with custom output path
npm run strapi openapi generate -- --output ./docs/api-spec.json
```

### `strapi templates:generate`

从当前 Strapi 项目创建模板。

🌐 Create a template from the current Strapi project.

```bash
strapi templates:generate <path>
```

- **strapi templates:generate &#60;路径&#62;**<br/>  在 `<path>` 生成一个 Strapi 模板

  示例：`strapi templates:generate ../strapi-template-name` 将会把所需的文件和文件夹复制到 `../strapi-template-name` 内的 `template` 目录

### `strapi ts:generate-types`

为项目模式生成 [TypeScript](/cms/typescript) 类型定义。

🌐 Generate [TypeScript](/cms/typescript) typings for the project schemas.

```bash
strapi ts:generate-types
```

- **strapi ts:generate-types --debug**<br />  在启用调试模式的情况下生成类型，显示生成的模式的详细表格。
- **strapi ts:generate-types --silent** 或 **strapi ts:generate-types -s**<br/>   在启用静默模式下生成类型，完全移除终端中的所有日志。不能与 `debug` 结合使用
- **strapi ts:generate-types --out-dir &#60;path&#62;** 或 **strapi ts:generate-types -o &#60;path&#62;**<br/>  生成类型定义，指定将创建文件的输出目录。

:::caution

Strapi 需要在 `types` 目录中生成项目类型才能正常工作。在大多数情况下，不应使用 `--out-dir` 选项。不过，在某些情况下，它可能很有用，例如在更改内容结构后生成第二个副本以比较现有类型和更新类型之间的差异。

🌐 Strapi requires the project types to be generated in the `types` directory for them to work. The `--out-dir` option should not be used for most cases. However, it can be useful for cases such as generating a second copy to compare the difference between your existing and updated types after changing your content structure.

:::

## 列表 {#listing}

🌐 Listing

这些命令会列出你 Strapi 项目中已注册的元素。

🌐 These commands list registered elements in your Strapi project.

### `strapi routes:list`

显示所有可用的[路线](/cms/backend-customization/routes)列表。

🌐 Display a list of all the available [routes](/cms/backend-customization/routes).

```bash
strapi routes:list
```

### `strapi policies:list`

显示所有已注册的[策略](/cms/backend-customization/policies)列表。

🌐 Display a list of all the registered [policies](/cms/backend-customization/policies).

```bash
strapi policies:list
```

### `strapi middlewares:list`

显示所有注册的 [中间件](/cms/backend-customization/middlewares) 列表。

🌐 Display a list of all the registered [middlewares](/cms/backend-customization/middlewares).

```bash
strapi middlewares:list
```

### `strapi content-types:list`

显示所有现有的 [内容类型](/cms/backend-customization/models) 列表。

🌐 Display a list of all the existing [content-types](/cms/backend-customization/models).

```bash
strapi content-types:list
```

### `strapi hooks:list`

显示所有可用钩子的列表。

🌐 Display a list of all the available hooks.

```bash
strapi hooks:list
```

### `strapi controllers:list`

显示所有注册的[控制器](/cms/backend-customization/controllers)列表。

🌐 Display a list of all the registered [controllers](/cms/backend-customization/controllers).

```bash
strapi controllers:list
```

### `strapi services:list`

显示所有注册的[服务](/cms/backend-customization/services)列表。

🌐 Display a list of all the registered [services](/cms/backend-customization/services).

```bash
strapi services:list
```
