CommonJS modules (runtime only)

If we compile the external module that we defined in the ES6 modules section into an CommonJS module (using the flag --compile commonjs), we will obtain the following CommonJS module:

var UserModel = (function () { 
    function UserModel() { 
      //... 
    } 
    return UserModel; 
})(); 
module.exports = UserModel; 

As we can see in the preceding code snippet, the CommonJS module definition syntax is almost identical to that of the legacy external module syntax. The main difference is the usage of the module object and its exports property instead of the exports keyword.

The preceding CommonJS module can be loaded natively by a Node.js application using the import keyword and the require function:

import UserModel = require('./UserModel'); ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.