4.12 Declaring CommonJS modules

CommonJS modules are in many ways very similar to AMD modules. When working with TypeScript we should avoid using CommonJS at design time. We should work with ES6 modules and leave the generation of CommonJS modules in the hands of the TypeScript compiler. One of the main advantages of CommonJS is that thy are natively supported by Node.js as opposed to AMD modules, which forces us to use a module loader like RequireJS in both web browsers and Node.js.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher.

How to do it

If we have a ES6 module like the following one:

import { IArrays } from '../../interfaces';

class Arrays implements IArrays {
  // …

export default new Arrays();

We can compile it into a CommonJS module using the module compilation flag as we can see in the following Gulp task:

gulp.task('build-es6-to-commonjs', function () {
    const tsProject = ts.createProject('tsconfig.json', {
        typescript: require('typescript'),
        module: 'commonjs'

    const input = './src/module_definitions/design_time/external/es6/*.ts';
    const output = './src/module_definitions/run_time/external/commonjs/';

    return gulp.src(input)

Note that the paths in the preceding Gulp tasks are the ones used in the companion source code. The ES6 modules are located un the the following module:


The resulting CommonJS modules are located under the following folder:


How it works

After compiling our ES6 module into JavaScript, the resulting AMD module will look as follows:

"use strict";
var Arrays = (function () {
    // ...
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = new Arrays();

CommonJS modules use an object named exports to declare the public parts of the module being defined. The preceding CommonJS module exports an object that has a property named default which takes the arrays object as its value. The TypeScript compiler adds an additional line:

Object.defineProperty(exports, "__esModule", { value: true });

As we learned in the recipes about AMD modules, this line is used to avoid compatibility issues with ES6 module loaders.

Source Code

Declaring CommonJS modules

See also

Please refer to the recipes about ES6 modules to learn about the declaration of external modules.

Shiv Kushwaha