Learn how to work with CommonJS modules in TypeScript, including importing, exporting, and configuring the TypeScript compiler for module systems.
In this section, we will explore the CommonJS module system, which is widely used in Node.js applications. We’ll learn how TypeScript interacts with CommonJS, how to import and export modules using CommonJS syntax, and how to configure the TypeScript compiler for different module systems. By the end of this section, you’ll have a solid understanding of how to work with CommonJS modules in TypeScript.
CommonJS is a module system that was designed to allow JavaScript to be used outside of the browser, primarily in server-side environments like Node.js. It provides a simple way to encapsulate code into modules, which can then be imported and used in other parts of an application.
module.exports
: This is the object that a module returns when it is required in another file. You can attach functions, objects, or variables to module.exports
to make them available to other modules.require()
: This function is used to import modules. It reads a JavaScript file, executes it, and returns the module.exports
object.Let’s look at how to use CommonJS syntax to import and export modules in TypeScript.
To export a module in CommonJS, you use the module.exports
object. Here is a simple example:
// mathUtils.ts
function add(a: number, b: number): number {
return a + b;
}
function subtract(a: number, b: number): number {
return a - b;
}
// Exporting functions using module.exports
module.exports = {
add,
subtract
};
In the example above, we define two functions, add
and subtract
, and export them using module.exports
. This makes these functions available to other modules that require mathUtils.ts
.
To import a module in CommonJS, you use the require()
function. Here’s how you can import the mathUtils
module we just created:
// app.ts
const mathUtils = require('./mathUtils');
const sum = mathUtils.add(5, 3);
const difference = mathUtils.subtract(5, 3);
console.log(`Sum: ${sum}`); // Output: Sum: 8
console.log(`Difference: ${difference}`); // Output: Difference: 2
In this example, we use require('./mathUtils')
to import the mathUtils
module. We can then use the add
and subtract
functions as if they were defined in app.ts
.
TypeScript supports both ES6 modules and CommonJS modules, and it’s important to understand how they can interoperate. ES6 modules use import
and export
syntax, which is different from CommonJS’s require()
and module.exports
.
TypeScript allows you to use ES6 import
and export
syntax even when targeting CommonJS. This can make your code cleaner and more consistent with modern JavaScript standards.
Here’s how you can rewrite the previous example using ES6 syntax:
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
// app.ts
import { add, subtract } from './mathUtils';
const sum = add(5, 3);
const difference = subtract(5, 3);
console.log(`Sum: ${sum}`); // Output: Sum: 8
console.log(`Difference: ${difference}`); // Output: Difference: 2
To ensure that TypeScript compiles your code correctly, you need to configure the module system in your tsconfig.json
file. This file contains various settings that tell the TypeScript compiler how to process your code.
Here’s an example tsconfig.json
that sets the module system to CommonJS:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "./dist",
"rootDir": "./src",
"strict": true
}
}
In this configuration:
"module": "commonjs"
specifies that the output should use the CommonJS module system."target": "es6"
sets the ECMAScript version to ES6."outDir": "./dist"
specifies the output directory for compiled JavaScript files."rootDir": "./src"
sets the root directory for TypeScript source files."strict": true
enables strict type-checking options.Now that we’ve covered the basics, try modifying the code examples above to experiment with CommonJS modules. Here are some suggestions:
mathUtils.ts
and export it. Then, import and use it in app.ts
.tsconfig.json
to esnext
and observe the differences in the compiled output.To help visualize how modules interact in a CommonJS system, let’s use a Mermaid.js diagram to represent the flow of module imports and exports.
graph TD; A[mathUtils.ts] -->|exports| B[app.ts]; B -->|requires| A;
This diagram shows that mathUtils.ts
exports functions, which are then required by app.ts
.
module.exports
to export functions, objects, or variables from a module.require()
to import modules in CommonJS.import
and export
syntax.tsconfig.json
to specify the module system and other options.For more information on CommonJS and module systems in JavaScript, check out the following resources: