UPDATE: Thanks to Yahiko Uzumaki on Twitter for pointing out that TypeScript Internal Modules are now called Namespace and External Modules are just called ‘Modules’. This Change can be seen in the release notes and the handbook on GitHub. Please keep that in mind as you read.

@BrettMN External modules should be simply called modules now, since internal modules are officially “namespaces”.

Last time in Intro to TypeScript 1.5 beta – Intro to Modules we talked about basic TypeScript modules features. In those examples we used only ‘internal’ modules. TypeScript has a concept called ‘external’ modules for use with Node.js or RequireJS. External modules specify relationships using import statements that consist of the keyword import a name that will be used for the module in the current file and the require keyword with the path the the file.

Referance Internal Module

Module.exportedFunctionOrClass();

Referance External Module

import localName = require('./ExternalModuelFileName');

With external modules the module keyword is not needed. The module is defined by what is in the one file. We still use the export keyword to make a class or function available for use outside of the module.

To configure the project to use modules I added a tsconfig.json file to the root of the project folder and added "module": "commonjs" to the list of options.

If we redid our previous Paths module as external modules they might look like this:

You may notice that the first this we do with the PathsExtended module imports the Paths module and then exports a function from it. This way the user of the PathsExtended module only needs to import one module to get all the functionality that was present before.

Exports = what?

With that last example we exported one function from the Paths module. To use that function we had to use the dot notation to access it. In situations like this we could us the export = syntax to simplify access. When the export = symbol is imported it is consumed directly and does not need the dot notation to get access to it.

Paths2.ts

This would probably make more sense if our module exported a class. Oh well, maybe next time.

Now we have an understanding of External modules and the export = syntax use it wisely. And be sure to stop by again soon as we will go over a few more details on TypeScript Modules in Intro to TypeScript 1.5 – Modules Remainders.