Skip to main content

使用 Strapi 的 TypeScript 开发

🌐 TypeScript development with Strapi

Page summary:

TypeScript 开发展示了 Strapi 类型定义以实现自动补全、使用 ts:generate-types 进行模式类型生成,以及通过 strapi()strapi.compile() 以编程方式启动服务器。本指南涉及插件构建和管理生成的类型定义。

在使用 Strapi 开发基于 TypeScript 的应用时,你可以:

🌐 While developing a TypeScript-based application with Strapi, you can:

Documents and entries

有关如何在基于 TypeScript 的项目中操作文档和条目的更多信息和最佳实践,请参阅 专门指南

🌐 More information and best practices on how to manipulate documents and entries with a TypeScript-based project can be found in the dedicated guide.

使用 Strapi TypeScript 类型定义

🌐 Use Strapi TypeScript typings

Strapi 在 Strapi 类上提供了类型定义,以增强 TypeScript 的开发体验。这些类型定义带有自动补齐功能,可以在开发时自动提供建议。

🌐 Strapi provides typings on the Strapi class to enhance the TypeScript development experience. These typings come with an autocomplete feature that automatically offers suggestions while developing.

要在开发 Strapi 应用时体验基于 TypeScript 的自动补齐功能,你可以尝试以下操作:

🌐 To experience TypeScript-based autocomplete while developing Strapi applications, you could try the following:

  1. 从你的代码编辑器中打开 ./src/index.ts 文件。

  2. @strapi/strapi 导入 Core 类型,并在全局 register 方法中将 strapi 参数声明为类型 Core.Strapi

    ./src/index.ts
    import type { Core } from '@strapi/strapi';

    export default {
    register({ strapi }: { strapi: Core.Strapi }) {
    // ...
    },
    };
  3. register 方法的主体中,开始输入 strapi. 并使用键盘箭头浏览可用属性。

  4. 从列表中选择 runLifecyclesFunctions

  5. 当添加 strapi.runLifecyclesFunctions 方法时,代码编辑器会返回一个可用生命周期类型的列表(即 registerbootstrapdestroy)。使用键盘箭头选择其中一个生命周期,代码将自动补齐。

为内容类型模式生成类型定义

🌐 Generate typings for content-types schemas

要为你的项目模式生成类型,请使用 ts:generate-types CLI 命令ts:generate-types 命令会在项目根目录下创建 types 文件夹,用于存储项目的类型。可选的 --debug 标志会返回生成的模式的详细表格。

🌐 To generate typings for your project schemas use the ts:generate-types CLI command. The ts:generate-types command creates the folder types, at the project root, which stores the typings for your project. The optional --debug flag returns a detailed table of the generated schemas.

要使用 ts:generate-types,请在项目根目录的终端中运行以下代码:

🌐 To use ts:generate-typesrun the following code in a terminal at the project root:

npm run strapi ts:generate-types --debug #optional flag to display additional logging
Tip: Automatically generate types

可以通过在 config/typescript.js|ts 配置文件 中添加 autogenerate: true 来在服务器重启时自动生成类型。

🌐 Types can be automatically generated on server restart by adding autogenerate: true to the config/typescript.js|ts configuration file.

Tip: Using types in your front-end application

要在前端应用中使用 Strapi 类型,你可以 use a workaround 直到 Strapi 实现官方解决方案。

修复生成类型的构建问题

🌐 Fix build issues with the generated types

可以排除生成的类型,以便实体服务不使用它们,而是使用不检查内容类型中可用的实际属性的宽松类型。

🌐 The generated types can be excluded so that the Entity Service doesn't use them and falls back on looser types that don't check the actual properties available in the content types.

要做到这一点,编辑 Strapi 项目的 tsconfig.json 并将 types/generated/** 添加到 exclude 数组中:

🌐 To do that, edit the tsconfig.json of the Strapi project and add types/generated/** to the exclude array:

./tsconfig.json
  // ...
"exclude": [
"node_modules/",
"build/",
"dist/",
".cache/",
".tmp/",
".strapi/",
"src/admin/",
"**/*.test.ts",
"src/plugins/**",
"types/generated/**"
]
// ...

然而,如果你仍然想在项目中使用生成的类型,但不希望 Strapi 使用它们,一个可行的解决方法是将这些生成的类型复制并粘贴到 generated 目录之外(这样在重新生成类型时,它们不会被覆盖),并从文件底部删除 declare module '@strapi/types'

🌐 However, if you still want to use the generated types on your project, but don't want Strapi to use them, a workaround could be to copy those generated types and paste them outside of the generated directory (so that they aren't overwritten when the types are regenerated) and remove the declare module '@strapi/types' from the bottom of the file.

Warning

类型应仅从 @strapi/strapi 导入以避免破坏性更改。@strapi/types 中的类型仅供内部使用,可能会在没有通知的情况下更改。

🌐 Types should only be imported from @strapi/strapi to avoid breaking changes. The types in @strapi/types are for internal use only and may change without notice.

以编程方式启动 Strapi

🌐 Start Strapi programmatically

要在 TypeScript 项目中以编程方式启动 Strapi,Strapi 实例需要指定已编译代码的位置。本节介绍如何设置和指明已编译代码目录。

🌐 To start Strapi programmatically in a TypeScript project the Strapi instance requires the compiled code location. This section describes how to set and indicate the compiled code directory.

使用 strapi() 工厂

🌐 Use the strapi() factory

可以通过使用 strapi() 工厂以编程方式运行 Strapi。由于 TypeScript 项目的代码会被编译到特定目录,因此应将参数 distDir 传递给工厂,以指示应从哪里读取已编译的代码:

🌐 Strapi can be run programmatically by using the strapi() factory. Since the code of TypeScript projects is compiled in a specific directory, the parameter distDir should be passed to the factory to indicate where the compiled code should be read:

./server.js

const strapi = require('@strapi/strapi');
const app = strapi.createStrapi({ distDir: './dist' });
app.start();

使用 strapi.compile() 函数

🌐 Use the strapi.compile() function

strapi.compile() 函数主要用于开发需要启动 Strapi 实例并检测项目是否包含 TypeScript 代码的工具。strapi.compile() 会自动检测项目语言。如果项目代码包含任何 TypeScript 代码,strapi.compile() 会编译代码并返回一个上下文,其中包含 Strapi 所需目录的特定值:

🌐 The strapi.compile() function should be mostly used for developing tools that need to start a Strapi instance and detect whether the project includes TypeScript code. strapi.compile() automatically detects the project language. If the project code contains any TypeScript code, strapi.compile() compiles the code and returns a context with specific values for the directories that Strapi requires:

const strapi = require('@strapi/strapi');

strapi.compile().then(appContext => strapi(appContext).start());

使用 TypeScript 开发插件

🌐 Develop a plugin using TypeScript

可以按照插件开发文档生成新插件,确保在CLI工具提示时选择“TypeScript”。

🌐 New plugins can be generated following the plugins development documentation, ensuring you select "TypeScript" when prompted by the CLI tool.

TypeScript 应用有两个重要的区别:

🌐 There are 2 important distinctions for TypeScript applications:

  • 创建插件后,在插件目录 src/admin/plugins/[my-plugin-name] 中运行 yarnnpm install 来安装插件的依赖。
  • 在插件目录 src/admin/plugins/[my-plugin-name] 中运行 yarn buildnpm run build 来构建包含该插件的管理面板。
Note

在初次安装后,无需重复执行 yarnnpm install 命令。执行 yarn buildnpm run build 命令是实现任何影响管理面板的插件开发所必需的。

🌐 It is not necessary to repeat the yarn or npm install command after the initial installation. The yarn build or npm run build command is necessary to implement any plugin development that affects the admin panel.