🐶
Node.js

Node.js ES6 Import: A How-To Guide

By Filip on 10/05/2024

Learn how to use ES6 import statements in your Node.js projects for cleaner and more maintainable code.

Node.js ES6 Import: A How-To Guide

Table of Contents

Introduction

Node.js developers are likely familiar with the require() function for importing modules, a key part of the CommonJS system. However, Node.js has embraced ES modules (ESM) using import and export, offering a modern approach to modularity. This article guides you on using ES modules in your Node.js projects.

Step-by-Step Guide

Node.js originally used the require() function for importing modules, which is part of the CommonJS module system. However, Node.js now supports ES modules (ESM) using the import and export keywords. Here's how to use ES modules in your Node.js projects:

1. Enable ES Modules

  • package.json: The most common way is to add "type": "module" to your project's package.json file. This tells Node.js to treat all .js files as ES modules.

    {
      "name": "my-project",
      "version": "1.0.0",
      "type": "module", 
      // ... other properties
    }
  • File Extension: Alternatively, you can use the .mjs file extension for your ES module files. This works even if you don't have "type": "module" in your package.json.

2. Exporting from a Module

Create a file (e.g., module.js) and export functions, classes, or variables using the export keyword:

// module.js
export function greet(name) {
  console.log(`Hello, ${name}!`);
}

export const PI = 3.14159;
  • Default Exports: You can have one default export per module:

    // module.js
    const message = "This is the default export";
    export default message; 

3. Importing into Another File

In another file (e.g., app.js), import what you need using the import keyword:

// app.js
import { greet, PI } from './module.js'; 
import myMessage from './module.js'; // Importing the default export

greet('John'); // Output: Hello, John!
console.log(PI); // Output: 3.14159
console.log(myMessage); // Output: This is the default export

Important Notes:

  • File Paths: When importing, you need to specify the relative path to the module file (e.g., './module.js').
  • Top-Level Await: You can use await directly at the top level of an ES module in Node.js.
  • CommonJS Interoperability: You can still use require() to import CommonJS modules within an ES module. However, to use ES modules in CommonJS, you'll need to use dynamic imports (import()).

Example:

// math.mjs (ES module)
export function add(a, b) {
  return a + b;
}

// app.js (ES module)
import { add } from './math.mjs';

console.log(add(5, 3)); // Output: 8

ES modules provide a more modern and standardized way to work with modules in Node.js, offering advantages like static analysis, better tree-shaking, and improved code organization.

Code Example

This code demonstrates the use of ES modules in Node.js. It includes a package.json file with "type": "module" to indicate ES module usage. The math.mjs file defines functions (add, subtract) and a constant (PI) which are exported using the 'export' keyword. The app.js file imports these functions and the constant from math.mjs and uses them to perform calculations. The code can be run from the terminal using the command 'node app.js'. This setup showcases the basic structure and syntax of ES modules in Node.js, emphasizing the use of 'export' and 'import' for modularity and code organization.

Here's a complete example demonstrating the use of ES modules in Node.js, along with explanations and ways to run the code:

Project Structure:

my-project/
├── package.json
├── math.mjs
└── app.js

1. package.json:

{
  "name": "my-project",
  "version": "1.0.0",
  "type": "module",
  "description": "Example using ES modules in Node.js"
}

2. math.mjs (ES Module):

// math.mjs
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export const PI = 3.14159;

3. app.js (ES Module):

// app.js
import { add, subtract, PI } from './math.mjs';

console.log(`5 + 3 = ${add(5, 3)}`);
console.log(`10 - 4 = ${subtract(10, 4)}`);
console.log(`Value of PI: ${PI}`);

Running the Code:

  1. From your terminal, navigate to the my-project directory.

  2. Run the following command:

    node app.js

Output:

5 + 3 = 8
10 - 4 = 6
Value of PI: 3.14159

Explanation:

  • package.json: The "type": "module" line is crucial. It tells Node.js to interpret all .js files as ES modules.
  • math.mjs: This file defines functions and a constant that we want to reuse. The export keyword makes them available for other modules to import.
  • app.js:
    • We use import to bring in the specific functions and the constant PI from math.mjs.
    • The imported functions and constant are then used like regular JavaScript elements.

Key Points:

  • File Extensions: While .mjs clearly identifies a file as an ES module, using "type": "module" in package.json allows you to use the familiar .js extension for all your modules.
  • Relative Paths: When importing, always use relative paths (e.g., './math.mjs') to specify the location of the module file relative to the current file.

This example demonstrates the fundamental concepts of using ES modules in Node.js. You can apply these principles to create more complex and organized projects with reusable components.

Additional Notes

  • Historical Context: Node.js initially relied on CommonJS due to its early development alongside the standardization of ES modules. The adoption of ES modules reflects Node.js's commitment to modern JavaScript standards.

  • Benefits of ES Modules:

    • Static Analysis: ES modules are statically analyzable, meaning code can be checked for errors and optimized during build time.
    • Tree-Shaking: Bundlers can eliminate unused exports, resulting in smaller bundle sizes for web applications.
    • Standardization: Aligns Node.js with browser-based JavaScript, promoting code reuse and a unified development experience.
  • Choosing Between CommonJS and ES Modules:

    • New Projects: ES modules are generally recommended for new Node.js projects due to their advantages.
    • Existing Projects: Migrating from CommonJS to ES modules in existing projects requires careful consideration and may involve code changes.
  • Dynamic Imports: The import() function allows for dynamically loading modules at runtime, which can be useful for lazy-loading or conditional imports.

  • Package Management: When publishing packages to npm, you can specify ES module support to ensure compatibility with projects using ES modules.

  • Community Resources: The Node.js ecosystem actively supports ES modules, with many libraries and frameworks providing ES module versions or guidance on their use.

  • Future of Modules in Node.js: ES modules are the future of modularity in Node.js, and their adoption is expected to continue growing.

Summary

Feature Description
Module System Node.js supports both CommonJS (require()) and ES modules (import/export).
Enabling ES Modules 1. Add "type": "module" to package.json to treat all .js files as ES modules. 2. Use the .mjs file extension for ES module files.
Exporting Use export to export functions, classes, or variables. Use export default for a single default export.
Importing Use import to import from other modules. Specify the relative file path.
Default Imports Import default exports directly using a variable name.
Top-Level Await await can be used at the top level of ES modules.
Interoperability require() can import CommonJS modules within ES modules. Dynamic import() is needed for the reverse.
Advantages of ES Modules - Static analysis - Better tree-shaking - Improved code organization

Conclusion

The transition to ES modules marks a significant advancement in Node.js development, aligning it with modern JavaScript standards and offering numerous benefits. By understanding how to enable, export, and import modules using the 'import' and 'export' keywords, developers can write more modular, maintainable, and performant code. While CommonJS remains a part of Node.js's history, embracing ES modules is essential for staying current with the evolving JavaScript landscape and leveraging the full potential of modern JavaScript development.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait