As I delve into the depths of TypeScript documentation to grasp the concept of modules, particularly ES6 modules, I stumbled upon some interesting insights.
typescript-modules - this documentation talks about typescript modules and highlights an important point:
Modules operate within their own confines, separate from the global scope. This essentially means that any variables, functions, classes, etc. defined within a module are not accessible outside unless specifically exported using one of the export mechanisms. Similarly, to utilize any entity exported from another module, it needs to be imported using designated import methods.
Furthermore, the documentation states that:
In TypeScript, akin to ECMAScript 2015, a file containing a top-level import or export statement is categorized as a module. Conversely, a file devoid of such declarations is treated as a script with its contents exposed in the global environment, thereby impacting how modules interact with it.
The notion here suggests that content within a file lacking import or export statements can potentially exist globally. However, practical observation tells a different story.
- folder
- script1.js
- script2.js
script1.js
var variable = "Hello";
script2.js
console.log(variable);
According to the documentation's claim, running script2.js should ideally display the value of the variable without issues since script1.js lacks import/export directives, making the variable globally accessible. But in reality, it throws an error. So, what exactly does it mean by stating that a script's content is available in the global scope?