Description
Bug Report
global scope If your file hasn't any import or export line, this file would be executed in global scope that all declaration in it are visible outside this file.
This is a hard edge case as there is really no way to tell if that file will run in CJS or ESM Context When there is no additional package.json or if it is a .ts and not a .cts or mts
🔎 Search Terms
Typescript 4.5+ moduleResolution GlobalScope Introduce var global inside ESM Context
🕗 Version & Regression Information
- This is a crash
- This changed between versions ______ and _______
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
- I was unable to test this on prior versions because _______
⏯ Playground Link
Playground link with relevant code
💻 Code
// inside CJS Context
// Your Code runs in the Global Context
var me = 'hi'
globalThis.me === me // true
// inside ESM Context
{
// Your Code is Wrapped into its own scope with access to the globalThis
var me = 'hi'
globalThis.me === me // false
}
🙁 Actual behavior
.mts and .ts files introduce none existing globals when the target Environment is "ECMAScript Module Context"
// xx.ts or xx.mts
// without declare keyword
var age: number
var magicGlobalString = 'It is Magic'
// other.ts
globalThis.age = 18 // no error
globalThis.magicGlobalString = 'NoError' // no error
That introduces now the following edge case TypeScript Assumes that .ts files without import or require get executed in the globalThis Context and with CJS that is correct! But Running the Same code in Module Context will not Introduce a Global Var on the globalThis Context.
🙂 Expected behavior
at last for .mts it should not introduce a new global. looking into package,json does not make clear if the target will be esm or cjs for the .ts extension it only shows the current development settings before compilation.
maybe the tsconfig target setting can be used i did not explore that fully but my first experiments show that a single target is well and should be keept while i see the need to define a full set of targets to process the input files right.
so the dev environment needs the be target environment aware while working with development files.
This is possible with the current target setting but many people develop for diffrent targets
/esm-target/
tsconfig.json <- with target ESNext
/cjs-target/
tsconfig.json <- with target ES2015
/src <- es6 + ts + cjs the problem is now the input files from src need to get handled differently in the IDE and Language Service based on the fact if it is compiled with the cjs-target or esm-target config
/tsconfig.json <- main config that gets extended by *-target/tsconfig.json
and the most best would be if we could get errors in the language server based on all existing tsconfig files and the target property