Baboo
Baboo

Reputation: 4278

How to move node app from javascript to typescript gradually

I have a javascript node application that is quiet big now and I want to switch to typescript to accelerate the development and better maintain the code. I installed typescript with node and mocha types with the commands

npm i typescript
npm i @types/node
npm i @types/mocha

I use a tsconfig.json file which is as follows:

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "dist",
        "sourceMap": true
    },
    "files": [
        "./node_modules/@types/mocha/index.d.ts",
        "./node_modules/@types/node/index.d.ts"
    ],
    "include": [
        "src/**/*.ts",
    ],
    "exclude": [
        "node_modules"
    ]
}

I added the "tsc": "tsc" script in the package.json to compile the code using the npm run tsc command.

Here is my project architecture:

- dist // created at compile time
- src
--- server.ts
--- configs
----- config.js
--- // other subdirectories
- package.json
- tsconfig.json

When I compile the code, it creates a dist folder that only contains the compiled server.ts file, the only file I renamed to .ts. So when I launch the compiled app with node dist/server.js all the other files are missing and the app crashes.

My question is: do I have to switch the whole application to typescript, renaming every file to .ts and changing imports or is there a way I can do it gradually and keep some javascript files?

Upvotes: 0

Views: 1004

Answers (1)

Baboo
Baboo

Reputation: 4278

As mentionned by Jeff in the comments of my post, here is how you can gradually switch to typescript. Base on the link Migrating from javascript documentation he provided, here is how I managed to make it work.

I changed the tsconfig.json file to:

{
    "compilerOptions": {
        "allowJs": true, // <-- option to allow js files as input in the ts compiler
        "target": "es6",
        "module": "commonjs",
        "outDir": "./dist",
        "sourceMap": true
    },
    "files": [
        "./node_modules/@types/mocha/index.d.ts",
        "./node_modules/@types/node/index.d.ts"
    ],
    "include": [
        "./src/**/*",
    ],
    "exclude": [
        "node_modules"
    ]
}

I also changed the package.json of the project to launch the app and run the tests from the compiled folder (which is dist in my case):

...
"scripts": {
    "start": "node ./dist/server.js",
    "test": "tsc && ./node_modules/.bin/mocha --recursive ./dist/test",
    "tsc": "tsc",
},
...

Upvotes: 1

Related Questions