Import/Export Vs Require/Module.exports

Import/Export

1) Named exports (several per module)

How to use lib.js?

Or

Note: You can also do export in the following ways as well.

2) Using the default export

If we want to export a single value or to have a fallback value for our module, we could use a default export:

Then, in another script, it will be straightforward to import the default export:

Note:
1) It is not possible to use var, let or const with export default.
2) You can’t have more than one default export.

require and module.exports

Best blog to read about in detail:
https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8

Some important points:
Requiring a folder
Modules don’t have to be files. We can also create a find-me folder under node_modules and place an index.js file in there. The same require('find-me') line will use that folder’s index.js file:
Note: An index.js file will be used by default when we require a folder, but we can control what file name to start with under the folder using the main property in package.json. For example, to make the require('find-me') line resolve to a different file under the find-me folder, all we need to do is add a package.json file in there and specify which file should be used to resolve this folder:

require.resolve

If you want to only resolve the module and not execute it, you can use the require.resolve function. This behaves exactly the same as the main require function, but does not load the file. It will still throw an error if the file does not exist and it will return the full path to the file when found.

Note :This can be used, for example, to check whether an optional package is installed or not and only use it when it’s available.

exports, module.exports, and synchronous loading of modules

A module object has ‘exports’ property.We can add any attribute to this special exports object. For example, let’s export an id attribute for index.js and lib/util.js:

The module.exports object in every module is what the require function returns when we require that module.

Note: All modules will be cached.
Node caches the first call and does not load the file on the second call.

We can see this cache by printing require.cache after the first require. The cache registry is simply an object that has a property for every required module. Those properties values are the module objects used for each module. We can simply delete a property from that require.cache object to invalidate that cache. If we do that, Node will re-load the module to re-cache it.

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store