2
votes

I have existing project in nodejs + express in javascript. Currently everything is working on es5.

Now i added typescript in same project and i want to do all the new development in typescript. But i am facing a issue in accessing existing javascript files.

I found that i can create definition file xx.d.ts (not sure if it is correct approach) of each existing javascript file and then use it in typescript files.

For example i have javscript file

myFile.js

function myClass(){
//some functions here associated with this variable
}

exports.myData = new myClass();

now i want to use it in my new ts file

So what i did in ts file to access is

declare function require(path: string): any;

var auth = require('./myFile').myData;

I am not sure if this is the right approach. Secondly i tried with myFile.d.ts file as well.

I defined this file in following way

declare module './myFile' {
  export var myData: any
}

But this gives error of relative path - TS2436 ambient module declaration cannot specify relative module path

Please let me know if anybody has any idea to resolve this problem or suggest if it is okay to go with first approach.

1
Have you try allowJS option in your tsconfig.json? - unional
github.com/Microsoft/dts-gen is a great tool to generate declaration files. - Siamand
@unional Thanks for the suggestion, I tried with that. But it gives different error regarding replacing exisiting file. ---- error TS5055: Cannot write file 'xx.js' because it would overwrite input file. There is one solution for this problem is to have different destination folder but i dont want that . - Manish Kumawat
@SiamandMaroufi I tried with this but it generate worst xx.d.ts files. It just write one line of code with export word. like - export 'path/xx.js"' This npm package is basically used to generate definition file of npm packages which has ts file. It will not work with js file. - Manish Kumawat
How do you manage your source control without a different destination folder? - unional

1 Answers

-1
votes

I found the solution long back but didnt posted here. Let me add the answer here so that it can help everyone

Make changes in tsconfig.json. Most important part here is types and typeRoots properties

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "declaration": true,
    "moduleResolution": "node",
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "lib": [ "es2015","dom" ]
  }
}

Now go to you package.json and add some type definition packages on the basis of need

 "@types/node": "~8.0.54",

After this configuration, nobody will get error and we dont need to separately specify declaration in each file