Compiling a Module in TypeScript
Back to: TypeScript Tutorial
TypeScript is a programming language that allows developers to write JavaScript code using static types. It supports modules, which are self-contained pieces of code that can be reused across multiple files or projects. Modules in TypeScript can be compiled to different formats, such as CommonJS, AMD, SystemJS, and ES6.
Compiling a module in TypeScript involves two steps:
- Write the module code
- Compile the module to a desired format
Let’s go through these steps in detail with a code example.
Step 1: Write the Module Code
Let’s say we want to create a module that exports a function that adds two numbers. Here’s the TypeScript code for the module:
// file: math.ts export function add(a: number, b: number): number { return a + b; }
In this code, we define a function called add
that takes two parameters a
and b
, both of type number
, and returns their sum as a number
. We also use the export
keyword to make the add
function available to other modules that import this module.
Step 2: Compile the Module
To compile the math
module, we need to use the TypeScript compiler (tsc
) and specify the output format. For example, to compile the module to CommonJS format, we can use the following command:
tsc --module commonjs math.ts
This command tells the TypeScript compiler to compile the math
module to CommonJS format and output the result to a file called math.js
. The resulting code in math.js
would look like this:
"use strict"; exports.__esModule = true; function add(a, b) { return a + b; } exports.add = add;
In this code, the exports
object is used to make the add
function available to other modules that import this module. The __esModule
flag is used to indicate that this module is a CommonJS module.
To use the math
module in another TypeScript file, we can import it like this:
// file: app.ts import { add } from './math'; const result = add(1, 2); console.log(result); // prints 3
In this code, we use the import
keyword to import the add
function from the math
module. We can then use the add
function to add two numbers.
In conclusion, compiling a module in TypeScript involves writing the module code and compiling it to a desired format using the TypeScript compiler. By using modules, developers can create reusable and modular code that can be shared across multiple files or projects.