为现有的 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.
要逐步将 TypeScript 文件添加到现有的 JavaScript 项目中,应在根 tsconfig.json 文件中将 TypeScript 标志 allowJs 设置为 true。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标志的代码复制到该文件中:
{
"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文件,并将以下代码复制到该文件中:
{
"extends": "@strapi/typescript-utils/tsconfigs/admin",
"include": [
"../plugins/**/admin/src/**/*",
"./"
],
"exclude": [
"node_modules/",
"build/",
"dist/",
"**/*.test.ts"
]
}
- (可选) 从项目根目录中删除
.eslintrc和.eslintignore文件。 - 在
database.ts配置文件的filename属性中添加一个额外的'..'(仅适用于 SQLite 数据库):
const path = require('path');
module.exports = ({ env }) => ({
connection: {
client: 'sqlite',
connection: {
filename: path.join(
__dirname,
"..",
"..",
env("DATABASE_FILENAME", ".tmp/data.db")
),
},
useNullAsDefault: true,
},
});
- 重建管理面板并启动开发服务器:
- Yarn
- NPM
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.