Two simple ways to use ES6 modules with Node.js.

I did a bunch of research into ES6 modules and Node.js and found two ways in which you can use ES6 modules in your own projects. Normally when you are working with Node.js you need to use common modules which is the syntax with module.exports = {} and require('express') you are used to in Node.js. ES6 modules on the other hand is the import express from 'express' syntax you are used to in the browser. The first way to use ES6 module syntax is by using a library called esm and the second is an experimental feature built into Node.js.

The safest way to use ES6 modules with Node.js currently is with the esm library. This library is unbelievably easy to use and can be setup with just a few lines of code. When you have a Node project, whether from running npm init or from an existing project, the first thing you need to do is install the library by running npm i esm. Once that is installed, the only thing left to do is modify the script in your package.json file that runs your server. You will need to add -r esm to the script. For example, go from node server.js to node -r esm server.js, or from nodemon server.js to nodemon -r esm server.js. Now you can start using ES6 modules inside your Node app and it will work exactly the same as before.

#node #es6 #javascript #developer

How To Use ES6 Modules With Node.js
26.40 GEEK