Modules Scripts and Declaration Files 7 exercises
explainer

Understanding Modules and Scripts in TypeScript

TypeScript offers two distinct ways to organize and execute code: modules and scripts.

Modules Have Local Scope

In TypeScript, a module is a file containing code that is executed within its own scope, not in the global scope. This means variables, functions, or types defined in a module are not

Loading explainer

Transcript

00:00 Let's talk about modules and scripts in TypeScript. On the left here, we have a module1.ts that has a MyModuleFunc sort of defined inside it. And then on the other side, we have module2.ts which has a MyModuleFunc called inside it. And you notice that module1 here and module2

00:19 both have an export inside them. Now, if you think about the history of TypeScript, TypeScript came from a time when most people would use scripts instead of modules. And let's think about the difference. A script is something that you put inside a HTML tag

00:36 and it puts all of the things defined inside it go into the global scope. Whereas a module, this lets you separate code out into different modules. And it means that MyModuleFunc is only declared within the scope of this module. But if I remove this export here,

00:54 then MyModuleFunc goes into the global scope. And now I can use it, even though this is itself a module, MyModuleFunc is now declared globally. And so I can use it like this. So TypeScript does some clever tricks here where it sees if there's any imports and exports inside your code.

01:13 And if there are, then it treats it as a module. But if there aren't, it treats it like a script. And anything you declare inside here, so I can say type MyModule equals just an empty object. And I can say type example equals MyModule. And I actually get auto-complete on that too.

01:32 And if I do a go to definition on MyModule, then I will jump to module one here. And you can notice here too that I've got a script inside there. So I've got script one, script two, and I can just use it without importing it. But of course, if I then add this back in, add the export back and I check inside module two,

01:51 now I'm getting errors here because I can't find name MyModuleFunc. It's not available anymore. Except of course, if I export it and then export type MyModule, now I can import it. So I'm now importing MyModuleFunc from module one and I can do the same with this type here. So MyModule, beautiful.

02:10 So that's the difference between modules and scripts. And by default, TypeScript uses this kind of check. It checks if there's any imports and exports. And if there are, it treats it as a module. If it doesn't, it treats it as a script and puts it in the global scope.