跳到主要内容

Adding TypeScript support to existing Strapi projects

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 support can be added to an existing Strapi project using the following procedure:

  1. 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. 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. (optional) Delete the .eslintrc and .eslintignore files from the project root.
  2. 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:
yarn build
yarn develop

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.