Modules
ES Modules
TypeScript supports ES Modules system introduced to JavaScript by ES6 (ES2015).
In ES Modules any file with a top-level export
, import
and/or await
statement is considered to be a module. A file without such a statement is considered to be a script and not a module.
Module statements and expressions are executed within their scope. Script statements and expressions are executed within the global scope.
To learn more about ES Modules see JavaScript Tutorial Modules.
TypeScript enhances ES modules with the possibility of exporting and importing types and enums.
While importing types optional prefix type
can be used to make code transpiling easier.
// types.ts
type qux = object[]
export enum Foo { A, B, C }
export type Bar = number[]
export type Baz = string[]
export default qux
// file1.ts
import qux, { Foo, Bar, type Baz } from './types'
// file2.ts
import type qux from './types'
The only reservation is that a type-only import cannot specify a default import and named bindings at the same time.
// file3.ts
import type qux, { type Baz } from './types'
// TS: A type-only import can specify a default import or named bindings, but not both.
CommonJS Modules
TypeScript supports CommonJS modules.
CommonJS exports identifiers using the global object module
and its method exports
.
// file1.ts
const foo = 42
const bar = '42'
module.exports = {
foo,
bar,
baz: 'forty two'
}
CommonJS imports identifiers using the global function require
.
// file2.ts
const els = require('./file1')
console.log(els) // {foo: 42, bar: '42', baz: 'forty two'}
Simultaneous usage of ES Modules and CommonJS in TypeScript
In TypeScript simultaneous usage of ES Modules and CommonJS Modules is possible but fraught with hazards. TypeScript has a set of compiler flags to cope with that.
Module Resolution
Module resolution is the process of locating the imported (the required) module based on the provided location string.
TypeScript has two strategies of module resolution:
-
Classic, and
-
Node.
The description of the strategies falls outside the scope of this tutorial.