I have spent some time reading the Typescript language specification and am somewhat confused about the difference between internal and external modules. Here is the description taken directly from the specification:
Internal modules (section 9.2.2) are local or exported members of other modules (including the global module and external modules). Internal modules are declared using ModuleDeclarations that specify their name and body. A name path with more than one identifier is equivalent to a series of nested internal module declarations.
External modules (section 9.4) are separately loaded bodies of code referenced using external module names. An external module is written as a separate source file that contains at least one import or export declaration. In addition, external modules can be declared using AmbientModuleDeclarations in the global module that directly specify the external module names as string literals. This is described further in section 0.
From what I've understood I think that external modules correspond to typescript files without enclosing module definitions that simply export a set of types and/or variables. From another typescript file I can simple import an external module in foo.ts with import foo = module("foo");
Can somebody explain to me the destinction between external and internal modules?
We can divide the module into two categories: Internal Module. External Module.
A module is a way which is used to organize the code in separate files and can execute in their local scope, not in the global scope. A namespace is a way which is used for logical grouping of functionalities with local scoping.
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).
Sections 9.3 and 9.4 of the specification explain this more clearly. I'll reproduce here some of the examples given in those sections.
Suppose the following code is in main.ts
.
import log = module("log"); log.message("hello");
This file references an external module log
, defined by whatever log.ts
exports.
export function message(s: string) { console.log(s); }
Notice that log.ts
doesn't use the module
keyword anywhere. It just exports things with export
.
This file has two internal modules, X.Y.Z
.
module A.B.C { import XYZ = X.Y.Z; export function ping(x: number) { if (x > 0) XYZ.pong(x – 1); } } module X.Y.Z { import ABC = A.B.C; export function pong(x: number) { if (x > 0) ABC.ping(x – 1); } }
These behave (mostly) like external modules, but they are contained in one file and you don't have to reference any outside files to use them. They have to be contained inside of a module
block when they are defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With