I have a large JavaScript codebase that I'd like to slowly transition to TypeScript. It's currently set up using CommonJS format, and in a perfect world I'd love to be able to just change one .js
file to .ts
at a time.
My tsconfig.json
looks like this:
{
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"target": "es5",
"module": "commonjs",
"noEmit": true,
"strict": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"types": [
"node"
],
},
"exclude": [
"node_modules"
]
}
And I've modified my start script to use ts-node -P tsconfig.json
. This seems to start everything up fine.
My problem lies with importing TS into JS. As I mentioned, it's currently set up using CommonJS, so module.exports
and require
. As an example, file-a.js
is requiring file-b.js
:
// file-a.js
const { exampleB } = require('../file-b');
// file-b.js
function exampleB() {
return "Hello World";
}
module.exports = {
exampleB,
};
When I change file-b.js
to .ts
, resolving any basic type checking issues, and then start the command I get the exception Error: Cannot find module '../file-b'
coming from file-a.js
.
I'm assuming this is Typescript having trouble resolving my CommonJS format. Is it possible for me to configure TypeScript to use this format and allow me to import TS files into JS as I slowly transition?
I'd even be fine changing all of my module.exports = { fn }
to export fn
if that helps.
This is what I've done:
some_folder
with tsconfig.json
, file-a.js
/(*), file-b.js
in it. All with the content you've provided.npm install -D ts-node
npm install -D typescript
npm install -D @types/node
'/home/.../some_folder/node_modules/.bin/ts-node' -P tsconfig.json file-a.js
and it worked.file-b.js
to file-b.ts
'/home/.../some_folder/node_modules/.bin/ts-node' -P tsconfig.json file-a.js
again... and it also worked just fine.So either you need to add much more context to your question, so that the problem you are facing can be reproduced, or start with creating a "template" Typescript project as simple as the one I've reproduced. Make sure it works, and only then start adding files from the original project of yours. Probably somewhere along the lines you've made some changes in a seemingly unrelated place and just can't see it.
(*) In you question you wrote ../file-b
and not ./file-b
. But for the clarity of the answer I skiped this detail. But I've also tried to place the file-b
outside of the project folder and tried to place file-a
in a subfolder. Everything works regardless.