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
require to import data
returning an object for multiple data
importing with destructuring from multiple exports
ES6 Imports
We can't directly use .js extension either we need to convert it to
.mjs or modify package.jsonWhen using imports we have to mention the extension as well
import greet from ./greet.js here adding .js is importantWe can use
npm init to generate a package.json fileAnd change the type attribute in
package.jsonBut with ES6 imports we lose access to
__dirname or __filename. For which we may have to rely on another packages like fs