This is some documentation I am writing mostly for myself and for anyone who might want to add typescript to their own projects.
The project we are adding typescript to can be found at https://github.com/tintindas/quotes-api
1. Making a new branch
Always make a new branch before screwing around with code that already works. Learnt this the hard way.
git checkout -b add-typescript
2. Adding typescript and required types as dev dependencies
The typescript compilers and the types of the libraries used in our project need to be added as developer dependencies so that we have access to all the type definitions we require.
npm install -D typescript @types/node @types/express @types/mongoose @types/cors
3. Make a tsconfig.json file
If you have typescript globally installed run
tsc --init
else run
npx tsc --init
4. Edit tsconfig.json
Edit the outDir and rootDir properties in the tsconfig file.
Set the rootDir to be the directory where all your logic is stored.
The outDir is the destination where the typescript transpiler puts all the files vanilla javascript files produced after transpilation.
"outDir": "./dist",
"rootDir": "./src",
I named my input directory src and the target directory dist
Set the include property to be src or whatever you have named your rootDir if there are typescript files you do not wish to be transpiled outside of the rootDir folder.
How my tsconfig.json file looks like
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
5. Create src directory and move all of your logic into it.
Anything outside of the src folder will not be put into the dist folder which will be our final production code.
6. Change extension .ts
Change the javascript files into typescript files by changing all the extensions to .ts.
This was the setup part of the project. VSCode should be screaming at you right now. Don't worry we will fix that in next part.
If you liked this post consider,
- checking out my projects at https://github.com/tintindas
- following me on twitter @tintin_das
Top comments (0)