0

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?

2
  • 1
    Check out the allowJs option and other advice discussed in the Migrating from JavaScript documentation Commented Oct 13, 2018 at 20:00
  • 1
    Thanks, that worked perfectly :ok_hand: Commented Oct 13, 2018 at 20:13

1 Answer 1

1

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",
},
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.