node

How to use ES6 import in Node


In this article, you will learn how to use es6 import in Node

What is ES6 import?
ES6 stands for version 6 of the ECMA Script programming language and an import statement is used to import modules that are exported by some other module.
A module is an encapsulated file that meets up with an external application on the basis of its related functionality. It allows you to write reusable code. The import modules are in strict mode whether you declare them or not.

How to use ES6 import in node?
The syntax for importing modules in ES6 looks like this.

import name from 'module-name'

// for example module name is express
import express from 'express'

There are different ways to import modules in ES6:

  1. The syntax for importing an entire module:
    import * as name from ‘module-name’
  2. The syntax for import default export from a module :
    import name from ‘module-name’
  3. The syntax for Importing a single export from a module:
    import { name } from ‘module-name’
  4. The syntax for Importing multiple exports from a module:
    import { nameOne , nameTwo } from ‘module-name’

Important :
If you try to run this code directly then you would get an error. The error will look something like this :

SyntaxError: Cannot use import statement outside a module

The reason for this error is that Node js doesn’t support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error.
Do not worry about the error! There is the solution for it.
Solution 1:
If you are using Node.js version 14.x.x or above then there is the simplest solution to fix it. All you have to do is to add “type”: “module” in your package.json file. like :

//package.json
{
  "name": "index",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  **"type": "module",**
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Solution 2:
If you are using any version below 14, you would have to use babel to fix it. To configure babel you have to follow few steps.

Step 1: install some required dev dependencies

npm install -D @babel/core @babel/preset-env @babel/node

Step 2: Create a babel.config.json file and add the following config

{
  "presets": ["@babel/preset-env"]
}

Step 3: Finally, you just have to use babel-node instead of node, so your start/dev script may look like this now

//package.json
{
  "name": "index",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

This is how you can use ES6 import in node.


Share on social media

//