0

I am new to TypeScript and am investigating migrating a large, existing ES2017-compliant NodeJS codebase to it.

Here's what my tsconfig.json looks like:

{
    "compilerOptions": {
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "./built",
        "allowJs": true,
        "target": "ES2017",
    },
    "include": [
        "**/*"
    ],
    "exclude": [
        "**/node_modules/**/*",
        "built"
    ]
}

If I rename all of my .js files to have .ts extensions, I experience this issue and see lots of Cannot redeclare block-scoped variable errors from tsc because TypeScript seemingly can't tell whether my files are modules (each with their own scope) or scripts (all share one scope).

These "dummy"/rote errors prevent me from seeing other, real errors that need to be fixed as part of the TypeScript migration.

So, my question is, what's the most sensible and correct way to resolve this issue as part of migrating an existing JavaScript codebase to TypeScript?

I thought of two options:

  1. Leave allowJs enabled and slowly rename each .js file to .ts one at a time, tweaking each file's imports/exports at the time each file is renamed, to indicate to TypeScript that the file is a module and won't conflict with other .ts files. (Existing .js files would just be copied over unaffected.)

  2. Rename all .js files to .ts and put a canned export {}; in every single file as a starting point. This doesn't seem ideal.

Neither of these options seems ideal. Is there a more straightforward way to tell tsc to treat all files as modules to prevent it from thinking that they will all share the same scope?

segfault
  • 572
  • 1
  • 7
  • 20
  • We just did this migration a couple of months ago and went with option #2. Just down and dirty to get it working. Then as we are working in the app on issues, we refactor as we go. You're going to have to migrate slowly because trying to add all of your types at once is a huge undertaking. Start with typing your low level components and then move outward. – VtoCorleone Jul 26 '18 at 16:08
  • @VtoCorleone To clarify, I am more curious about getting the project in a good "starting state" for a migration where I can start gradually trying to add types, I have no intention of trying to add them all at once. I was hoping there was a less hacky approach than option #2, but I guess a hack is better than nothing. :) – segfault Aug 01 '18 at 03:50

1 Answers1

0

As of TypeScript 4.7, this is solved via "moduleDetection": "force" in your tsconfig.json:

{
  "compilerOptions": {
    // ... Various options here, such as module ...
    "moduleDetection": "force"
  }
}   

Reference: https://www.typescriptlang.org/tsconfig#moduleDetection

Original Github issue which drove this config: https://github.com/microsoft/TypeScript/issues/14279

lance.dolan
  • 3,493
  • 27
  • 36