Here are examples of steps taken to convert a server rendered web app to TypeScript. In my experience you can expect a conversion like this to take a day or a couple of days for a small project (a couple of thousand lines of code).
Install Typescript and types for node and dependencies:
npm install typescript --save-dev
npm install @types/node --save-dev
npm install @types/koa --save-dev
npm install @types/koa-router -save-dev
npm install @types/koa-bodyparser -save-dev
npm install @types/lodash --save-dev
npm install @types/redis --save-dev
Create the file:
$(npm bin)/tsc --init
Edit the file and set basic compilerOptions etc:
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"baseUrl": "src",
"outDir": "./dist",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
echo dist >> .gitignore
Add to package.json:
{
"scripts": {
"build": "tsc"
}
}
for file in $(find src -iname '*.js'); do git mv $file "${file%.js}.ts"; done
npm install ts-jest --save-dev
npm install @types/jest --save-dev
npx ts-jest config:init
npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
Edit .eslintrc.js:
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
};
You can configure nodemon to work with TypeScript or you can use ts-node-dev instead of nodemon:
npm install ts-node-dev --save-dev
In package.json:
{
"scripts": {
"dev": "ts-node-dev -r dotenv-defaults/config --respawn --transpileOnly src/index.ts"
}
}
npm run build
Tip: if you don't know how to type something you can use any
as an escape hatch. It basically tells the compiler to skipe type checking.
- Change all require statements to import statements. Tip: if you use
import * as myModule from './myModule'
then you don't need a default export in the module. - Change all Common.js
exports
andmodule.exports
statements to corresponding ES moduleexport
anddefault export
statements.
Here are example scripts in package.json:
"scripts": {
"build": "tsc",
"start": "npm run build && node -r dotenv-defaults/config dist/index.js",
"dev": "ts-node-dev -r dotenv-defaults/config --respawn --transpileOnly src/index.ts",
"lint": "eslint --ext .ts src",
"test": "npm run lint && jest ---setupFiles dotenv-defaults/config"
}