24
ES6 is the Node way to go
How many of us still use the old ES syntax in our NodeJS apps?
const express = require('express');
const app = express()
app.use(express.static('public'));
app.get('/',function (req,res) {
res.send('ES what?');
})
app.listen(3000, function () {
console.log('App listening on port 3000!')
})
I bet most of us do, and unfortunately I am equally guilty of this! The reason we continue to use this syntax with node is because most templates and sample codes are based on this. But since the release of Node 14.x, ES modules is officially supported and stable. But one shouldn't migrate just because its the thing to do. Migrations often involved weighing the pros and cons. After a little research and experimentation, I have concluded that there are actually three big advantages to using ES6's import
over require
:
-
import
helps in selectively loading the pieces of code which are required -
import
also helps in saving memory loaded onto the app -
require()
's loading is synchronous whileimport
's loading can be asynchronous; this provides large apps with a performance edge.
So the natural question is what would it take to use an ES6 syntax in your node project?
Let's get started!
One thing to note, Node.js doesn’t support ES6 import directly. If we try to use the keyword import
for importing modules in Node.js, it will undoubtedly throw an error. For example, if we try to import express module, Node.js will error as follows:
In order to enable Node support for ES modules we need to tweak the package.json file. In the package.json
file add "type": "module"
to the root of the file as such:
//package.json
{
"name": "index",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC"
"dependencies": {
"express": "~4.16.1",
}
}
Then run the following command to update changes to package.json
npm i
Once we have updated our package
file we have to make the relevant changes to our app's code as follows:
import express from 'express';
const app = express();
app.get('/',(req,res) => {
res.send('ES6 is the Node way to go');
})
app.listen(3000,() => {
console.log(`App listening on port 3000!`);
})
Run your app and it should work with the updated ES syntax!
I recently update my demo app Random Cat Facts to use the new syntax and would recommend checking out the update ES6 commit diff for a real world example of this migration.
Thank you for following along and be sure to look out for my next post!
==== Follow me on Social Media(@mrinasugosh
) ====
Dev.to: @mrinasugosh
Github: @mrinasugosh
Twitter: @mrinasugosh
LinkedIn: @mrinasugosh
24