Skip to content

CommonJS globals permitted for ES module builds with no compiler error.Β #58658

@knightedcodemonkey

Description

@knightedcodemonkey

πŸ”Ž Search Terms

nodenext, module, __dirname

πŸ•— Version & Regression Information

Version 5.4.5

⏯ Playground Link

No response

πŸ’» Code

package.json

"type": "module"

tsconfig.json

{
  "compilerOptions": {
    "module": "NodeNext"
  },
  "include": ["src"]
}

file.ts

console.log(__dirname)

πŸ™ Actual behavior

No compiler error, but this causes a runtime error in Node:

ReferenceError: __dirname is not defined in ES module scope

πŸ™‚ Expected behavior

That the compiler issues an error similar to the inverse situation.

For example, when targeting CommonJS:

package.json

"type": "commonjs"

file.ts

console.log(import.meta.dirname)

The compiler issues the following error:

error TS1470: The 'import.meta' meta-property is not allowed in files which will build into CommonJS output.

Additional information about the issue

Perhaps there is a good reason for this that I'm not understanding, but I would think tsc should issue an error or warning for any syntax that would produce a runtime error.

Here is a more complete example: https://github.com/knightedcodemonkey/tsc-module-globals

  • npm install
  • npm run esm (note no compile error but the output causes a runtime error)
  • npm run cjs (note there is a compile error)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions