4.13 Importing CommonJS modules

In the preceding recipe we learned how to declare CommonJS modules in this recipe we will learn how to import CommonJS modules.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher, Gulp, Browserify and the gulp-typescript plugin.

How to do it

Let’s take a look to the ES6 ndrscr module included in the companion source code:

import arrays from './arrays';
import collections from './collections';
import functions from './functions';
import objects from './objects';
import utility from './utility';

const VERSION = '1.0.0';
export { VERSION, arrays, collections, functions, objects, utility };

When compiled into a CommonJS module it looks as follows:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var arrays_1 = require("./arrays");
var collections_1 = require("./collections");
var functions_1 = require("./functions");
var objects_1 = require("./objects");
var utility_1 = require("./utility");

var VERSION = "1.0.0";

exports.arrays = arrays_1.default;
exports.collections = collections_1.default;
exports.functions = functions_1.default;
exports.objects = objects_1.default;
exports.utility = utility_1.default;

How it works

As we can see in the preceding code snippet, CommonJS modules use a function named require to import other external modules and the exports object to declare the public parts of the module being defined. One of the main things that we should notice is that (as opposed to AMD modules) there are no callbacks here because CommonJS modules are not loaded asynchronously.

See also

Please refer to the recipes about ES6 to learn about the declaration of external modules. Refer to the recipes about AMD and UMD to learn more about these module definition syntaxes. You can also refer to the first chapter to learn more about Gulp.

Shiv Kushwaha