Modules

TypeScript modules are quite similar to ES6 modules, so you should be familiar with their construct already. Modules enable encapsulation and reuse, and allow dependency order resolution.

The scope of TypeScript modules are bound to files. Every file is a module and its internal declarations should not conflict with anything external. When a module desires to expose a declaration, such as a function, class, and even a constant, you can use the export keyword. On the other hand, if a module needs an exported member from another module, the import keyword is used.

Moreover, the TypeScript compiler supports generating TypeScript modules out to several formats, for example, CommonJS, ES6, and more. This means that you can use TypeScript with different module loaders, including Node.js and Webpack.

Just like ES6, TypeScript modules support default, named, and wildcard import and export statements. Consider the following exported utility functions that have been implemented in the log.ts file:

// log.ts

export default
function(o: any) { console.log(o); }

export function logArray(o: any[]) {
console.log(`Array (length: ${o.length}`, o);
}

function appLog(o: any) { console.log('MyApp Log Entry', o); }
export { appLog };

When another file needs to use these functions, it looks like this:

// app.ts

import log, { logArray as logA, appLog } from './log';

import * as logUtils from './log';

log(5);
logA([2, 3]);
appLog(4);
logUtils.default(5);
logUtils.logArray([2, 3]);
logUtils.appLog(5);

As you can see, the format is identical to standard ES6 modules.

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

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