Home > Mobile >  How do I prevent tsc from including browser types in the compliation
How do I prevent tsc from including browser types in the compliation

Time:12-03

I have a script that uses ts-node:

#!/usr/binenv ts-node

const top: number[] = [];

but tsc complains:

top3.ts(3,7): error TS2451: Cannot redeclare block-scoped variable 'top'.

because apparently top is a global variable in browsers.

I've installed @types/node and my tsconfig.json reads:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "target": "es6",
    "types": ["node"],
  }
}

so I can refer to node builtins like process.

How do I configure tsc so that it does not include browser builtins, but only pure ECMAScript node.js builtins?

CodePudding user response:

To prevent tsc from including browser types in the compilation, you can use the "lib" option in your tsconfig.json file. This option allows you to specify the library files that should be included in the compilation.

To only include pure ECMAScript and node.js builtins, you can set the "lib" option to ["es6", "dom", "node"]. This will exclude any browser-specific types from the compilation.

Here is an example of how your tsconfig.json file would look with this configuration:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es6",
        "types": ["node"],
        "lib": ["es6", "dom", "node"]
    }
}

With this configuration, tsc will only include ECMAScript, node.js, and dom builtin types in the compilation, and will not include any browser-specific types. This should resolve the error you are seeing with the variable 'top' being redeclared.

CodePudding user response:

Yes, you are correct. The "dom" option in the "lib" configuration includes the browser-specific types that are causing the error with the variable 'top' being redeclared.

To prevent this error, you can either remove the "dom" option from the "lib" configuration, or you can rename the variable 'top' to something else that does not conflict with any browser-specific types.

Here is an example of how your tsconfig.json file would look without the "dom" option in the "lib" configuration:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es6",
        "types": ["node"],
        "lib": ["es6", "node"]
    }
}

Alternatively, you can rename the variable 'top' to something else that does not conflict with any browser-specific types. For example, you could rename it to 'topNumbers' or 'topList':

const topNumbers: number[] = [];

or

const topList: number[] = [];

Either of these solutions should prevent the error from occurring.

  • Related