How To Use ES6 Import Statement In Node.js

Node.js has long been known for its support of CommonJS modules, using require and module.exports for module management. However, with the advent of ECMAScript 6 (ES6), JavaScript introduced a more modern and concise syntax for working with modules through import and export statements.

In this tutorial, we’ll explore how to use ES6 import statements in Node.js, enabling you to write more modular and expressive code.

Best Way to Enable ES6 Modules in Node.js

There are two primary methods to use es6 import in your node app: using the .mjs extension or setting the "type" field to "module" in your package.json.

But, the most preferable way to do this is by adding the "type":"module" in your package.json file. Here is the example:

Using “type”: “module” in package.json

1. Set “type”: “module” in package.json:

// package.json
{
    "type": "module",
    "scripts": {
        "start": "node main.js"
    }
}
adding type module in node package.json file

2. Create a Module (e.g., myModule.js):

// myModule.js
export const myFunction = () => {
    console.log('Hello from myFunction!');
};

3. Import in Your Main File (e.g., main.js):

// main.js
import { myFunction } from './myModule.js';

myFunction(); // Output: Hello from myFunction!

Benefits of ES6 Import Statements

  1. Cleaner Syntax: ES6 import statements offer a more concise and readable syntax compared to the traditional require syntax.
  2. Named Exports: ES6 modules allow for named exports, making it easy to export multiple functions or variables from a single module.
  3. Consistency Across Frontend and Backend: If you’re working on a project with both frontend and backend code, using ES6 import statements provides a consistent syntax.
  4. Tree-Shaking: ES6 modules enable tree-shaking, a process where unused code is eliminated during the bundling phase, resulting in smaller bundle sizes.

Conclusion:

Embracing ES6 import statements in Node.js can significantly improve the modularity and readability of your code. Whether you choose the .mjs extension or set "type": "module" in your package.json, the transition to ES6 modules is a step toward a more modern and expressive JavaScript codebase.