向现有 Strapi 项目添加 TypeScript 支持
¥Adding TypeScript support to existing Strapi projects
向现有项目添加 TypeScript 支持需要添加 2 个 tsconfig.json
文件并重建管理面板。此外,还可以选择删除 eslintrc
和 eslintignore
文件。
¥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.
应在根 tsconfig.json
文件中将 TypeScript 标志 allowJs
设置为 true
,以将 TypeScript 文件增量添加到现有 JavaScript 项目中。allowJs
标志允许 .ts
和 .tsx
文件与 JavaScript 文件共存。
¥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:
-
在项目根目录添加一个
tsconfig.json
文件,并将以下带有allowJs
标志的代码复制到该文件中:¥Add a
tsconfig.json
file at the project root and copy the following code, with theallowJs
flag, to the file:
{
"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/**"
]
}
-
在
./src/admin/
目录下添加tsconfig.json
文件,并将以下代码复制到该文件中:¥Add a
tsconfig.json
file in the./src/admin/
directory and copy the following code to the file:
{
"extends": "@strapi/typescript-utils/tsconfigs/admin",
"include": [
"../plugins/**/admin/src/**/*",
"./"
],
"exclude": [
"node_modules/",
"build/",
"dist/",
"**/*.test.ts"
]
}
-
(可选)从项目根目录中删除
.eslintrc
和.eslintignore
文件。¥(optional) Delete the
.eslintrc
and.eslintignore
files from the project root. -
在
database.ts
配置文件中的filename
属性中添加额外的'..'
(仅 SQLite 数据库需要):¥Add an additional
'..'
to thefilename
property in thedatabase.ts
configuration file (only required for SQLite databases):
const path = require('path');
module.exports = ({ env }) => ({
connection: {
client: 'sqlite',
connection: {
filename: path.join(
__dirname,
"..",
"..",
env("DATABASE_FILENAME", ".tmp/data.db")
),
},
useNullAsDefault: true,
},
});
-
重建管理面板并启动开发服务器:
¥Rebuild the admin panel and start the development server:
- Yarn
- NPM
```sh
yarn build
yarn develop
```
npm run build
npm run develop
将在项目根目录下添加一个 dist
目录(参见 项目结构),并且该项目可以访问与新的 TypeScript 支持的 Strapi 项目相同的 TypeScript 功能。
¥A dist
directory will be added at the project root (see project structure) and the project has access to the same TypeScript features as a new TypeScript-supported Strapi project.