Skip to main content

TypeScript 开发

¥TypeScript development

TypeScript 在 JavaScript 之上添加了一个额外的类型系统层,这意味着现有的 JavaScript 代码也是 TypeScript 代码。Strapi 在 v4.3.0 及更高版本的新项目中支持 TypeScript。现有的 JavaScript 项目可以通过转换程序进行 添加 TypeScript 支持。支持 TypeScript 的项目允许使用 TypeScript 开发插件以及使用 TypeScript 类型。

¥TypeScript adds an additional type system layer above JavaScript, which means that existing JavaScript code is also TypeScript code. Strapi supports TypeScript in new projects on v4.3.0 and above. Existing JavaScript projects can add TypeScript support through a conversion procedure. TypeScript-enabled projects allow developing plugins with TypeScript as well as using TypeScript typings.

🤓 TypeScript 入门

要开始使用 TypeScript 进行开发,请使用 CLI 安装文档 创建一个新的 TypeScript 项目。对于现有项目,可以添加 TypeScript 支持 使用提供的转换步骤。此外,项目结构TypeScript 配置 部分还具有特定于 TypeScript 的资源,用于理解和配置应用。

¥To start developing in TypeScript, use the CLI installation documentation to create a new TypeScript project. For existing projects, TypeScript support can be added with the provided conversion steps. Additionally, the project structure and TypeScript configuration sections have TypeScript-specific resources for understanding and configuring an application.

开始使用 TypeScript 进行开发

¥Start developing in TypeScript

启动支持 TypeScript 的项目的开发环境需要在启动服务器之前构建管理面板。在开发模式下,应用源代码被编译到 ./dist/build 目录,并随着 Content-type Builder 中的每次更改重新编译。要启动应用,请在根目录中运行以下命令:

¥Starting the development environment for a TypeScript-enabled project requires building the admin panel prior to starting the server. In development mode, the application source code is compiled to the ./dist/build directory and recompiled with each change in the Content-type Builder. To start the application, run the following commands in the root directory:

npm run build
npm run develop

使用 TypeScript 类型

¥Use TypeScript typings

Strapi 提供了 Strapi 类的类型,以改善 TypeScript 开发体验。这些类型具有自动补齐功能,可以在开发时自动提供建议。

¥Strapi provides typings on the Strapi class to improve the TypeScript developing 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 文件。

    ¥From your code editor, open the ./src/index.ts file.

  2. register 方法中,将 strapi 参数声明为 Strapi 类型:

    ¥In the register method, declare the strapi argument as of type Strapi:

    ./src/index.ts
    import { Strapi } from "@strapi/strapi";

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

    ¥Within the body of the register method, start typing strapi. and use keyboard arrows to browse the available properties.

  4. 从列表中选择 runLifecyclesfunctions

    ¥Choose runLifecyclesfunctions from the list.

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

    ¥When the strapi.runLifecyclesFunctions method is added, a list of available lifecycle types (i.e. register, bootstrap and destroy) are returned by the code editor. Use keyboard arrows to choose one of the lifecycles and the code will autocomplete.

生成项目模式的类型

¥Generate typings for project 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
💡 提示:JavaScript 项目的类型生成

对于 JavaScript 项目,可以关闭自动类型生成(参见 config/typescript.js 文档)。

¥For JavaScript projects, automatic types generation can be turned off (see config/typescript.js documentation).

💡 提示:在前端应用中使用类型

要在前端应用中使用 Strapi 类型,你可以 使用解决方法,直到 Strapi 实现官方解决方案,你将在 这篇博客文章 中找到更多信息。

¥To use Strapi types in your front-end application, you can use a workaround until Strapi implements an official solution, and you will find additional information in this blog article.

修复生成类型的构建问题

¥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/",
"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' on the bottom of the file.

⚠️ 警告

类型只能从 @strapi/strapi 导入,以避免重大更改。@strapi/types 中的类型仅供内部使用,如有更改,恕不另行通知。

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

使用 TypeScript 开发插件

¥Develop a plugin using TypeScript

可以在 插件开发文档 之后生成新的插件。TypeScript 应用有两个重要的区别:

¥New plugins can be generated following the plugins development documentation. There are 2 important distinctions for TypeScript applications:

  • 创建插件后,在插件目录 src/admin/plugins/[my-plugin-name] 中运行 yarnnpm install 来安装插件的依赖。

    ¥After creating the plugin, run yarn or npm install in the plugin directory src/admin/plugins/[my-plugin-name] to install the dependencies for the plugin.

  • 在插件目录 src/admin/plugins/[my-plugin-name] 中运行 yarn buildnpm run build 以构建包含插件的管理面板。

    ¥Run yarn build or npm run build in the plugin directory src/admin/plugins/[my-plugin-name] to build the admin panel including the plugin.

✏️ 注意

初次安装后无需重复执行 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.

以编程方式启动 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({ 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());

向现有 Strapi 项目添加 TypeScript 支持

¥Add TypeScript support to an existing Strapi project

向现有项目添加 TypeScript 支持需要添加 2 个 tsconfig.json 文件并重建管理面板。此外,还可以选择删除 eslintrceslintignore 文件。应在根 tsconfig.json 文件中将 TypeScript 标志 allowJs 设置为 true,以将 TypeScript 文件增量添加到现有 JavaScript 项目中。allowJs 标志允许 .ts.tsx 文件与 JavaScript 文件共存。

¥Adding TypeScript support to an existing project requires adding 2 tsconfig.json files and rebuilding the admin panel. Additionally, the eslintrc and eslintignore files can be optionally removed. The TypeScript flag allowJs should be set to true in the root tsconfig.json file to incrementally add TypeScript files to existing JavaScript projects. The allowJs flag allows .ts and .tsx files to coexist with JavaScript files.

可以使用以下过程将 TypeScript 支持添加到现有的 Strapi 项目中:

¥TypeScript support can be added to an existing Strapi project using the following procedure:

  1. 在项目根目录添加一个 tsconfig.json 文件,并将以下带有 allowJs 标志的代码复制到该文件中:

    ¥Add a tsconfig.json file at the project root and copy the following code, with the allowJs flag, to the file:

./tsconfig.json
{
"extends": "@strapi/typescript-utils/tsconfigs/server",
"compilerOptions": {
"outDir": "dist",
"rootDir": ".",
"allowJs": true //enables the build without .ts files
},
"include": ["./", "src/**/*.json"],
"exclude": [
"node_modules/",
"build/",
"dist/",
".cache/",
".tmp/",
"src/admin/",
"**/*.test.ts",
"src/plugins/**"
]
}
  1. ./src/admin/ 目录下添加 tsconfig.json 文件,并将以下代码复制到该文件中:

    ¥Add a tsconfig.json file in the ./src/admin/ directory and copy the following code to the file:

./src/admin/tsconfig.json
{
"extends": "@strapi/typescript-utils/tsconfigs/admin",
"include": ["../plugins/**/admin/src/**/*", "./"],
"exclude": ["node_modules/", "build/", "dist/", "**/*.test.ts"]
}
  1. (可选)从项目根目录中删除 .eslintrc.eslintignore 文件。

    ¥(optional) Delete the .eslintrc and .eslintignore files from the project root.

  2. database.ts 配置文件中的 filename 属性中添加额外的 '..'(仅 SQLite 数据库需要):

    ¥Add an additional '..' to the filename property in the database.ts configuration file (only required for SQLite databases):

./config/database.ts


const path = require("path");



module.exports = ({ env }) => ({
connection: {
client: "sqlite",
connection: {
filename: path.join(
__dirname,
"..",
"..",
env("DATABASE_FILENAME", ".tmp/data.db")
),
},
useNullAsDefault: true,
},
});
  1. 重建管理面板并启动开发服务器:

    ¥Rebuild the admin panel and start the development server:

npm run build
npm run develop

完成上述过程后,将在项目根目录添加 dist 目录,并且该项目可以访问与支持 TypeScript 的新 Strapi 项目相同的 TypeScript 功能。

¥After completing the preceding procedure a dist directory will be added at the project root and the project has access to the same TypeScript features as a new TypeScript-supported Strapi project.