Node.js - enable ES Modules (enabling import/export)

3 points
Created by:

In this article, we would like to show you how to enable ES Modules (import / export keyword) in Node.js.

Quick solution: 

Put the following line inside package.json file:

"type": "module"


When you are using "type": "module" in your project, you need to specify file extension while importing modules (e.g import { myConstant } from './myModule.js').



Practical example

Below, we present how to change module.exports and require() to use export / import keywords instead.

Project structure:

 ├── index.js
 ├── module1.js
 └── package.json

Simple steps to enable ESM:

1. Go to the package.json file in your project and insert the following line:

"type": "module"

Example package.json file:

  "name": "my-app",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"

2. After you have saved the package.json with "type": "module" inside, you would be able to use import / export keywords.

Usage example

1. Export constant from module1.js file:

export const myConstant = 'my constant example value';

2. Import the constant inside index.js file:

import { myConstant } from './module1.js'



my constant example value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂