NodeJS does not support ES6 import directly, by default. If you try to use ‘import’ for importing modules it will throw an error. Good news is that NodeJS has started supporting ES6 import on an experimental basis. In this article, we will look at how to use ES6 import in NodeJS.
The main advantage of using import over require in NodeJS is that import allows you to import only required methods and packages while require imports the entire module, thereby increasing processing time and memory consumption.
How to Use ES6 Import in NodeJS
Here are the steps to enable ES6 import in NodeJS.
1. Open package.json
package.json file is normally located in the root folder of your NodeJS project. If you cannot find it there, then look into the package’s folder in node_modules subfolder.
Every npm package has package.json in it. Open the package.json for the package you want to import, in a text editor. For our example, we open package.json for ExpressJS package located in node_modules folder.
$ sudo node_modules/expressjs/package.json
2. Enable ES6 import
Just add {“type”: “module” in the package.json file.
{ "name": express, "type": "module", ... }
3. Test ES6 import
Let us create a test server app.js to test ES6 import. It runs a server on port 80 and displays “Hello World” in console when you access its home URL.
$ sudo vi app.js
Add the following lines in it.
import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('Hello World'); }) const PORT = 80; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`); })
4. Start NodeJS server
Start NodeJS server
$ sudo node app.js
Open browser and visit http://localhost or http://127.0.0.1. You will see the message “Hello World”.
If you see any error messages, then try installing esm module and then running the above command with -r esm option
$ sudo npm install esm $ sudo node -r esm app.js
If you still see any error message saying that import token is not supported then run the above server with –experimental-modules option as shown in the following command.
$ sudo node --experimental-modules app.js
If it still doesn’t work for you, or if you are using NodeJS <= v12, then rename app.js to app.mjs (.mjs file extension) and run it using the above command.
$ sudo node --experimental-modules app.mjs
Using one of the above ways, you should be able to import modules in NodeJS. In most cases, the errors are due to your NodeJS not being able to support ES6 imports.
Also read :
How to Download File in NodeJS Server
How to Prevent Direct Access to PHP File
How to Fix NGINX Upsteam Timed Out Error
How to Install more_set_headers in NGINX
How to Modify Response Headers in NGINX
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.