Languages
[Edit]
EN

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

3 points
Created by:
Jun-L
413

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"

 

Practical example

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

Project structure:

/app/
 ├── 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'

console.log(myConstant);

Output:

my constant example value
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.

❤️💻 🙂

Join