Modules

How JavaScript Modules are Defined

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.

Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

Modules are executed within their own scope, not in the global scope. This means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.

Non-modules

Before we start, it’s important to understand what TypeScript considers a module. The JavaScript specification declares that any JavaScript files without an import declaration, export, or top-level await should be considered a script and not a module.

Inside a script file variables and types are declared to be in the shared global scope, and it’s assumed that you’ll either use the outFile compiler option to join multiple input files into one output file, or use multiple <script> tags in your HTML to load these files (in the correct order!).

If you have a file that doesn’t currently have any imports or exports, but you want to be treated as a module, add the line:

Try this code ↗

export {};

which will change the file to be a module exporting nothing. This syntax works regardless of your module target.

Modules in TypeScript

Additional Reading:Impatient JS (Modules) ↗MDN: JavaScript Modules ↗

There are three main things to consider when writing module-based code in TypeScript:

  • Syntax: What syntax do I want to use to import and export things?
  • Module Resolution: What is the relationship between module names (or paths) and files on disk?
  • Module Output Target: What should my emitted JavaScript module look like?

ES Module Syntax

A file can declare a main export via export default:

Try this code ↗

// @filename: hello.ts
exportdefaultfunctionhelloWorld() {
console.log("Hello, world!");
}

This is then imported via:

Try this code ↗

import helloWorld from "./hello.js";
helloWorld();

In addition to the default export, you can have more than one export of variables and functions via the export by omitting default:

Try this code ↗

// @filename: maths.ts
exportvarpi = 3.14;
exportletsquareTwo = 1.41;
exportconstphi = 1.61;

exportclassRandomNumberGenerator {}

exportfunctionabsolute(num: number) {
if (num < 0) returnnum * -1;
returnnum;
}

These can be used in another file via the import syntax:

Try this code ↗

import { pi, phi, absolute } from "./maths.js";

console.log(pi);
constabsPhi = absolute(phi);

const absPhi: number

Additional Import Syntax

An import can be renamed using a format like import {old as new}:

Try this code ↗

import { pi as π } from "./maths.js";

console.log(π);

(alias) var π: number
import π

You can mix and match the above syntax into a single import:

Try this code ↗

// @filename: maths.ts
exportconstpi = 3.14;
exportdefaultclassRandomNumberGenerator {}

// @filename: app.ts
importRandomNumberGenerator, { piasπ } from"./maths.js";

RandomNumberGenerator;

(alias) class RandomNumberGenerator
import RandomNumberGenerator

console.log(π);

(alias) const π: 3.14
import π

You can take all of the exported objects and put them into a single namespace using * as name:

Try this code ↗

// @filename: app.ts
import*asmathfrom"./maths.js";

console.log(math.pi);
constpositivePhi = math.absolute(math.phi);

const positivePhi: number

You can import a file and not include any variables into your current module via import "./file":

Try this code ↗

// @filename: app.ts
import"./maths.js";

console.log("3.14");

In this case, the import does nothing. However, all of the code in maths.ts was evaluated, which could trigger side-effects which affect other objects.

TypeScript Specific ES Module Syntax

Types can be exported and imported using the same syntax as JavaScript values:

Try this code ↗

// @filename: animal.ts
exporttypeCat = { breed: string; yearOfBirth: number };

exportinterfaceDog {
breeds: string[];
yearOfBirth: number;
}

// @filename: app.ts
import { Cat, Dog } from"./animal.js";
typeAnimals = Cat | Dog;

TypeScript has extended the import syntax with two concepts for declaring an import of a type:

import type

Which is an import statement which can only import types:

Try this code ↗

// @filename: animal.ts
exporttypeCat = { breed: string; yearOfBirth: number };
exporttypeDog = { breeds: string[]; yearOfBirth: number };
exportconstcreateCatName = () =>"fluffy";

// @filename: valid.ts
importtype { Cat, Dog } from"./animal.js";
exporttypeAnimals = Cat | Dog;

// @filename: app.ts
importtype { createCatName } from"./animal.js";
constname = createCatName();
Generated error
'createCatName' cannot be used as a value because it was imported using 'import type'.
Inline type imports

TypeScript 4.5 also allows for individual imports to be prefixed with type to indicate that the imported reference is a type:

Try this code ↗

// @filename: app.ts
import { createCatName, typeCat, typeDog } from"./animal.js";

exporttypeAnimals = Cat | Dog;
constname = createCatName();

Together these allow a non-TypeScript transpiler like Babel, swc or esbuild to know what imports can be safely removed.

ES Module Syntax with CommonJS Behavior

TypeScript has ES Module syntax which directly correlates to a CommonJS and AMD require. Imports using ES Module are for most cases the same as the require from those environments, but this syntax ensures you have a 1 to 1 match in your TypeScript file with the CommonJS output:

Try this code ↗

import fs = require("fs");
constcode = fs.readFileSync("hello.ts", "utf8");

You can learn more about this syntax in the modules reference page.

CommonJS Syntax

CommonJS is the format which most modules on npm are delivered in. Even if you are writing using the ES Modules syntax above, having a brief understanding of how CommonJS syntax works will help you debug easier.

Exporting

Identifiers are exported via setting the exports property on a global called module.

Try this code ↗

function absolute(num: number) {
if (num < 0) returnnum * -1;
returnnum;
}

module.exports = {
pi:3.14,
squareTwo:1.41,
phi:1.61,
absolute,
};

Then these files can be imported via a require statement:

Try this code ↗

const maths = require("./maths");
maths.pi;

any

Or you can simplify a bit using the destructuring feature in JavaScript:

Try this code ↗

const { squareTwo } = require("./maths");
squareTwo;

const squareTwo: any

CommonJS and ES Modules interop

There is a mis-match in features between CommonJS and ES Modules regarding the distinction between a default import and a module namespace object import. TypeScript has a compiler flag to reduce the friction between the two different sets of constraints with esModuleInterop.

TypeScript’s Module Resolution Options

Module resolution is the process of taking a string from the import or require statement, and determining what file that string refers to.

TypeScript includes two resolution strategies: Classic and Node. Classic, the default when the compiler option module is not commonjs, is included for backwards compatibility. The Node strategy replicates how Node.js works in CommonJS mode, with additional checks for .ts and .d.ts.

There are many TSConfig flags which influence the module strategy within TypeScript: moduleResolution, baseUrl, paths, rootDirs.

For the full details on how these strategies work, you can consult the Module Resolution.

TypeScript’s Module Output Options

There are two options which affect the emitted JavaScript output:

  • target which determines which JS features are downleveled (converted to run in older JavaScript runtimes) and which are left intact
  • module which determines what code is used for modules to interact with each other

Which target you use is determined by the features available in the JavaScript runtime you expect to run the TypeScript code in. That could be: the oldest web browser you support, the lowest version of Node.js you expect to run on or could come from unique constraints from your runtime - like Electron for example.

All communication between modules happens via a module loader, the compiler option module determines which one is used. At runtime the module loader is responsible for locating and executing all dependencies of a module before executing it.

For example, here is a TypeScript file using ES Modules syntax, showcasing a few different options for module:

Try this code ↗

import { valueOfPi } from "./constants.js";

exportconsttwoPi = valueOfPi * 2;

ES2020

Try this code ↗

import { valueOfPi } from "./constants.js";
exportconsttwoPi = valueOfPi * 2;

CommonJS

Try this code ↗

"use strict";
Object.defineProperty(exports, "__esModule", { value:true });
exports.twoPi = void0;
constconstants_js_1 = require("./constants.js");
exports.twoPi = constants_js_1.valueOfPi * 2;

UMD

Try this code ↗

(function (factory) {
if (typeofmodule === "object" && typeofmodule.exports === "object") {
varv = factory(require, exports);
if (v !== undefined) module.exports = v;
    }
elseif (typeofdefine === "function" && define.amd) {
define(["require", "exports", "./constants.js"], factory);
    }
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value:true });
exports.twoPi = void0;
constconstants_js_1 = require("./constants.js");
exports.twoPi = constants_js_1.valueOfPi * 2;
});

Note that ES2020 is effectively the same as the original index.ts.

You can see all of the available options and what their emitted JavaScript code looks like in the TSConfig Reference for module.

TypeScript namespaces

TypeScript has its own module format called namespaces which pre-dates the ES Modules standard. This syntax has a lot of useful features for creating complex definition files, and still sees active use in DefinitelyTyped ↗. While not deprecated, the majority of the features in namespaces exist in ES Modules and we recommend you use that to align with JavaScript’s direction. You can learn more about namespaces in the namespaces reference page.

Last updated on