Skip to content

When using require() in es modules, no TS2441 error occurs and node_modules/@types is automatically included in the project.Β #48726

@jespertheend

Description

@jespertheend

Bug Report

πŸ”Ž Search Terms

cjs require

πŸ•— Version & Regression Information

  • This changed between versions 4.0.5 and 4.2.3

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

// @filename: index.js
// @checkJs: true

/**
 * @param {string} str
 */
function require(str) {}

const someModule = require("google-closure-compiler");

export {someModule};

πŸ™ Actual behavior

TS2792 occurs at the call to require():

const someModule = require("google-closure-compiler");
//                         ^^^^^^^^^^^^^^^^^^^^^^^^^----- Cannot find module 'google-closure-compiler'. option?
//                                                        Did you mean to set the 'moduleResolution' option to 'node',
//                                                        or to add aliases to the 'paths'

What's worse, if the project contains types in node_modules/@types, these will now be included in the project, regardless of the value set for "typeRoots": [] in tsconfig.json, which is supposed to prevent this sort of behaviour.

From https://www.typescriptlang.org/tsconfig#typeRoots:

If typeRoots is specified, only packages under typeRoots will be included.

For me this caused a long and painful process of figuring out why I kept getting errors for imports missing from the "path" module, even though I definitely disabled node imports.

Here you can download a reduced test case of the situation described above.

Run tsc --noEmit -p jsconfig.json in the folder and you'll get an error stating that fromFileUrl is not in the "path" module, even though node_modules/@types has been disabled and a custom path has been added in jsconfig.json.

πŸ™‚ Expected behavior

Either no error, or an error informing me that I can't use require() as it's already taken by the compiler. The latter is already the case with TypeScript files:

function require(str: string) {}
//       ^^^^^^^------ TS2441: Duplicate identifier 'require'.
//                     Compiler reserves name 'require' in top level scope of a module.

It's just missing inside JavaScript files.

πŸ”ƒ Workarounds

Just don't name your functions require πŸ˜…. But you'd have to know that this issue is happening in the first place, which is not easy to figure out with no errors telling you this.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issueHas ReproThis issue has compiler-backed repros: https://aka.ms/ts-reprosWorking as IntendedThe behavior described is the intended behavior; this is not a bug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions