Modules & ES6 Imports

Modules & ES6 Imports

These are used to make certain functionality public. There are two ways to do this by using the CommonJS Module or by implementing the newer ES6 way.
  • The commonjs is not supported in browser context and there we can only rely on es6 way
  • The es6 can and should be used in node environment

Common JS Modules

module.exports to export data
notion image
require to import data
notion image
returning an object for multiple data
notion image
importing with destructuring from multiple exports
notion image

ES6 Imports

We can't directly use .js extension either we need to convert it to .mjs or modify package.json
When using imports we have to mention the extension as well import greet from ./greet.js here adding .js is important
notion image
We can use npm init to generate a package.json file
notion image
And change the type attribute in package.json
notion image
notion image
But with ES6 imports we lose access to __dirname or __filename. For which we may have to rely on another packages like fs
notion image