Search code examples
typescripttsc

'Cannot redeclare block-scoped variable' in unrelated files


There is a simple TS package that is used as CommonJS modules and has no exports. TS files are compiled to JS files with the same name and used as require('package/option-foo').

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5"
  }
}

option-foo.ts:

declare const GlobalVar: any;

function baz() {}

if (GlobalVar.foo) GlobalVar.baz = baz;

option-bar.ts:

declare const GlobalVar: any;

function baz() {}

if (GlobalVar.bar) GlobalVar.baz = baz;

The important part here is that option-foo and option-bar are never used together. There are other complimentary TS files in the project, but they don't affect anything, just needed to be transpiled to JS in one tsc run.

When tsc runs, it throws

Cannot redeclare block-scoped variable 'GlobalVar'.

Duplicate function implementation.

Cannot redeclare block-scoped variable 'GlobalVar'.

Duplicate function implementation.

for GlobalVar and baz in both files.

How can this be treated without complicating build process or the output from these two TS files?


Solution

  • 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