DEV Community

Cover image for JavaScript Modules 101: import & export Without Confusion
Kunal
Kunal

Posted on

JavaScript Modules 101: import & export Without Confusion

As JavaScript project grows managing code become more important than just writing it.
Modules provide a simple way to organize, reuse and maintain code efficiently.

In this blog we will cover :

  • Why modules are needed
  • Exporting functions or values
  • Importing modules
  • Default vs named exports
  • Benefits of modular code

Modules

Before modules JavaScript don't have a proper way to organize code. Everything lived in global scope which often caused conflicts and messy code.

Developers used tricks like global variables or IFFE to manage this.


// Global variable (problem: can be overwritten)

var count = 0;
function increment() {
  count++;
}
Enter fullscreen mode Exit fullscreen mode

// IIFE (used to avoid global pollution)

(function(){
var count = 0 

function increment(){
 count++
console.log(count())

increment()
})()
Enter fullscreen mode Exit fullscreen mode

But these were just workarounds, not a real solution.

Here comes the modules

A module is simply a separate piece of code with its own scope. It helps to keep the code organized , reusable and avoid conflicts that used to happen with global variable.

JavaScript supports various modules system. Here we only focus on the two most important types


Types of modules

  1. ES6 Modules

ES6 modules (ECMA Script 6) it is a native module in this you can group and only share what's needed using import and export keywords.

Exporting a Module

To create a module you define the code you want to expose using the export keyword.
You can export individually or entire module object


 export const PI = 3.14 
 export function add(a , b){
        return a + b
 }

Enter fullscreen mode Exit fullscreen mode

You can also export multiple things as a group:


const MULTIPLY = 'multiply';
const SUBTRACT = 'subtract';

export { MULTIPLY, SUBTRACT };

Enter fullscreen mode Exit fullscreen mode

Importing a Module

To use the exported functionalities in another file, you use the import keyword. Hereโ€™s how you can import both named and default exports:

import { PI, add } from './math.js';

// Default export
import myFunction from './myFunction.js';
Enter fullscreen mode Exit fullscreen mode
  1. CommonJS Modules

Before ES6 modules, JavaScript (especially in Node.js) used CommonJS to manage code between files. Instead of import and export, it used require to bring code in and module.exports to send code out.

Exporting with CommonJS

const PI = 3.14;
function add(a, b) {
    return a + b;
}

module.exports = { PI, add };

Enter fullscreen mode Exit fullscreen mode

Importing with CommonJS

const math = require('./math.js');
console.log(math.add(2, 3)); // Outputs: 5
Enter fullscreen mode Exit fullscreen mode

Default Modules

Modern JavaScript lets you load files only when you actually need them using dynamic imports.

Instead of loading everything at once, you can load parts later making your app faster and lighter, especially in big projects.

// math.js (module)
export default function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode
// app.js (using it)
import add from './math.js';

console.log(add(2, 3)); // 5
Enter fullscreen mode Exit fullscreen mode

Default vs named exports

Feature Named Export Default Export
Number of exports Multiple allowed Only one per file
Import syntax import { add } from './file' import add from './file'
Naming Must match exact name Can use any name
Curly braces Required {} Not required
Use case Export multiple utilities/functions Export one main functionality

Benefits of modular code

  1. Better Organization

Modules keep your code clean and structured, so itโ€™s easier to read and manage as your project grows.

  1. Reusability

You can reuse modules anywhere in your app (or even in other projects), saving time and effort.

  1. No Naming Conflicts

Each module has its own scope, so same variable names wonโ€™t clash with each other.

  1. Easy Testing

Smaller modules are easier to test individually, which makes your code more reliable.


Thanks for reading ! if enjoyed this blog , you can read more on this ๐Ÿ‘‡

Top comments (0)