Import vs Require in JavaScript. CommonJS vs ES modules.
Tags: javascript, beginners, programming
Published: 2023-01-01 17:29:13

## Introduction

If you are new to javascript and/or node and have been confused by keywords like `import`, `export` , `module.exports` and `require`, then you are not alone. In this short piece, I want to clear that up for you.

## CommonJS:

Introduced in 2009, the CommonJS module solved a major problem JavaScript had for a long time. CommonJS made it easy to define and share the modules (or pieces of code) between files. CommonJS is designed to run on the server and uses `module.exports` to export and `require()` import the code.

* CommonJS modules are **synchronous**, meaning that the `require()` function will block the execution of the script until the required module is fully loaded.
    
* CommonJS modules use a pattern called "global leaky bucket", in which variables declared in a CommonJS module is added to the global scope and are therefore accessible to all other modules.
    
* CommonJS is Primarily used in Node projects.
    

### Using Common JS modules.

* **Exporting single function.**
    

```javascript

//foo.js 
const greeting = (name)=> console.log(`Hello! ${name}`)

// if you want to share it, export it\
module.exports = greeting
```

* Importing and using the code.
    

```javascript

// bar.js

// Importing:  
const greeting = require(./foo.js)

// Using it 
const welcome = (place) => console.log(`${greeting(Pratik)}. Welcome ${place}`)
```

> * In the above code: `require()` takes in file path as argument.
>     
> * While `requiring` module from another file, you can exclude `.js` extension.
>     
> * `require` can be used inside other functions.
>     

* **Exporting multiple functions.**
    

```javascript

//foo.js
const greeting = (name)=> console.log(`Hello! ${name}`)
const greeting_VIP = () => /*Code Here*/ 

module.exports = {
greeting,
greeting_VIP
}
```

* Importing multiple functions
    

```js

// bar.js
const {greeting, greeting_VIP} = require('./foo.js')

// then call individual function like: 
greeting('Pratik'); // expected Output: Hello! Pratik
greeting_VIP()
```

> We can also import the above code with `const foo = require(./foo.js)`. But while using it, you need to call them like this: `foo.greeting(argument)`. To make it easy, we destructured it while importing the function. Read more about [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) here.

* An alternate way to export the code.
    

```javascript

//foo.js
exports.greeting = () => {/*code here*/}
exports.greeting_VIP = () => {/*code here*/}
```

## ES Modules.

Introduced in ECMAScript 6 (ES6), the JavaScript version released in 2015, ECMAScript (ES) modules are designed to be used in the browser and are optimized for performance. ES modules are the official module system for JavaScript and are designed to be used in the browser and on the server.

ES modules use the `export` and `import` statements to define and consume modules. They also use a pattern called "explicit exports", in which variables must be explicitly exported and imported in order to be shared between modules. This helps to prevent the "global leaky bucket" pattern that is used in CommonJS modules, in which variables declared in a module are added to the global scope and are therefore accessible to all other modules.

### Using ES6 Modules.

* **Exporting only one function.**
    

```js

//foo.js

const greeting = (name)=> console.log(`Hello! ${name}`)
const greeting_VIP = (name)=> console.log(`Hello! ${name}. You are VIP`) 

  
export default greeting // only exports greeting.
```

* Importing
    

```js

// bar.js
import greeting from './foo.js'
```

> `.js` extension is required in ES6 `import`

* Import the module in a `HTML` file like so.
    

```html

<body> 
<script src='./foo.js' type='module'> </script>
</body>
%% type='module' is required %% 
```

* You can **export** multiple functions/variables  like this in ES6
    

```js

//foo.js
export const greeting = (name)=> console.log(`Hello! ${name}`)
export const greeting_VIP = (name)=> console.log(`Hello! ${name}. You are VIP`)
```

* importing the module into another file
    

```js

//bar.js
import {greeting, greeting_VIP} from './foo.js' // same destructuring pattern.
```

* `import` can't be used inside other functions.
    
* It does not matter where you put import in the file, `js` will sort them at the top anyway.
    

## Conclusion:

If you are starting a new Node.js project, it is generally recommended to use ECMAScript (ES) modules. However, to use ES modules in a Node.js project, you will need to ensure that you are using a version of Node.js that supports ES modules. Node.js 14 and higher supports ES modules natively so that you can use the `import` and `export` statements directly in your code.

Suppose you are using an earlier version of Node.js that does not support ES modules natively. In that case, you can still use ES modules in your project by using a tool like Babel to transpile your code to a version of JavaScript that is compatible with the version of Node.js you are using.

In my experience, in a large company, both ECMAScript (ES) modules and CommonJS modules are used. So, you need to know both ways.