Node.js - enable ES Modules (enabling import/export)
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"
Note:
When you are using
"type": "module"
in your project, you need to specify file extension while importing modules (e.gimport { myConstant } from './myModule.js'
).
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