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:
- Add a
tsconfig.jsonfile at the project root and copy the following code, with theallowJsflag, 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/**"
]
}
- Add a
tsconfig.jsonfile 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"
]
}
- (optional) Delete the
.eslintrcand.eslintignorefiles from the project root. - Add an additional
'..'to thefilenameproperty in thedatabase.tsconfiguration 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,
},
});
- Rebuild the admin panel and start the development server:
- Yarn
- NPM
yarn build
yarn develop
npm run build
npm run 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.