External modules

External modules are pretty much the solution we need when it comes to building applications designed to grow. Basically, each external module works at a file level, where each file is the module itself and the module name will match the filename without the .js extension. We do not use the module keyword anymore and each member marked with the export prefix will become part of the external module API. The internal module depicted in the previous example would turn into this once conveniently saved in the Greetings.ts file:

export class Greeting {
constructor(public name: string) {
console.log(`Hello ${name}`);
}
}

export class XmasGreeting {
constructor(public name: string) {
console.log(`Merry Xmas ${name}`);
}
}

Importing this module and using its exported classes would require the following code:

import greetings = require('Greetings');
var XmasGreetings = greeting.XmasGreetings();
var xmasGreetings = new XmasGreetings('Pete');
// console outputs 'Merry Xmas Pete'

Obviously, the require function is not supported by traditional JavaScript, so we need to instruct the compiler about how we want that functionality to be implemented in our target JavaScript files. Fortunately, the TypeScript compiler includes the --module parameter in its API, so we can configure the dependency loader of choice for our project: commonjs for node-style imports, amd for RequireJS-based imports, umd for a loader implementing the Universal Module Definition specification, or system for SystemJS-based imports. We will focus on the SystemJS module loader throughout this book:

tsc --outFile app.js --module commonjs

The resulting file will be properly shimmed, so modules can load dependencies across files using our module loader of choice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset