Basics of Modules in JavaScript

Modules are independent lines of code that have a certain functionality as denoted by their files.

A few years back, JavaScript was only a few lines of code used to enhance the HTML pages and we didn’t need our “modules” back then. Fast forward a few more years, now JS is the backbone of many web applications which brings the necessity to know how to structure our JS code.

Modules system starting from nowhere to currently emerging ES6 module, there will be a lot to cover. In this article let’s discuss the basics of modules in the Common JS module system.

Common JS modules

It is the default module structure that NodeJS supports.

The most common syntax for importing any installed package or library is :

const path = require(‘path’); // import statement
const { a ,b ,c } = require('file') //named import

Named Imports

At some point in time, we all have come across this. We use it to import files.
We have named imports to simultaneously import multiple objects, functions, or variables from a file. Here we are destructuring the imported module so that only the required modules are imported.

const a=9,b =8,c=44,d=0; 
module.exports = { a ,b , c , d as default} // default export of d

Default Exports can be only one per module. Something exported as default can be imported by any name and not necessarily the same as the original name.

Modularising code is one of the best practices in coding. There’s more to it but this would be enough to just get started.

Thanks for reading !!

By the way, 👏🏻 *clap* 👏🏻 your hands (up to 50x) if you enjoyed this post. It encourages me to keep daily writing and help other people finding it :)

--

--

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