JavaScript Modules: Using `import` and `export`

Escape the chaos of a single global scope and learn to write clean, reusable, and maintainable code with JavaScript's native module system.

🐛

Welcome! Let's clean up our JavaScript. In the past, all code lived in one global space, which could get messy.

var user = 'Admin';
function login() {...}
// ... 1000 lines later ...
var user = 'Guest'; // Oops! 🐛

Why Use Modules? The Problem of a Global Scope

Before modules, all JavaScript code in a browser shared a single global scope. This meant variables from one script could clash with another, causing bugs. Modules solve this by creating a private scope for each file. Nothing is shared unless you explicitly say so.

Sharing Your Code: The `export` Statement

The export statement is used to make variables, functions, or classes available to other modules. You can have multiple named exports from a single file, or one default export. This is like deciding which tools from your workshop you want to lend out.

Using Shared Code: The `import` Statement

The import statement is used to bring in functionalities that another module has exported. You can import specific named exports using curly braces {...} or import the default export directly. This is like borrowing a specific tool you need for your project.

Connecting the Files: `type="module"`

To make this work in a browser, you must tell the HTML that your script is a module. You do this by adding the type="module" attribute to your <script> tag. This signals the browser to handle imports and exports correctly.

Practice Zone


Interactive Test 1: Sort the Logic

Drag the code blocks to their correct positions to create a working module system.

Arrastra en el orden correspondiente.


Arrastra las opciones:

import { greet } from './utils.js';
greet('World');
export function greet(name) { ... }

Completa el código:

// utils.js______
// main.js______
// The result______
Unlock with Premium

Interactive Test 2: Complete the Syntax

Rellena los huecos en cada casilla.

// math.js
 const PI = 3.14;

// app.js
 { PI } from './math.js';
console.log('The value of PI is ' + PI);
Unlock with Premium

Practice Example: Create a Module

In saludo.js, export a function called `saludar` that takes a name and returns `"Hola, [name]!"`. In `app.js`, import that function and call it with the name "Mundo".

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

// archivo saludo.js export function saludar(nombre) { return `Hola, ${nombre}!`; } // archivo app.js import { saludar } from './saludo.js'; saludar("Mundo");
Unlock with Premium

Knowledge Check

What is the primary purpose of the `export` keyword in a JavaScript module?


Unlock with Premium

Modules in the Real World

ES Modules (`import`/`export`) are the standard for modern JavaScript and are the backbone of frameworks like React, Vue, and Angular, as well as server-side environments like Node.js.


1. In React Components

Every React component is a module. You typically create a component in its own file and use a default export, then import it wherever it's needed.

// Button.js
export default function Button() {
  return <button>Click</button>;
}

// App.js
import Button from './Button.js';

2. In Node.js

While Node.js traditionally used a different system (CommonJS, with `require()` and `module.exports`), it now fully supports ES Modules. You can enable it by setting `"type": "module"` in your `package.json` file.

// package.json
{
  "name": "my-app",
  "type": "module"
}

// server.js
import fs from 'fs'; // Built-in node module
📦

3. The Role of Bundlers

For complex web apps, developers use tools called **bundlers** (like Vite or Webpack). They read all your `import` and `export` statements, bundle all your modules into one or more optimized files for the browser, and handle other assets like CSS and images.

// Your project files
- app.js
- utils.js
- component.js

  ↓ Vite / Webpack

// Browser gets this
- bundle.min.js
📜📜📜 ➡️ 📜

Practical Takeaway: Mastering `import` and `export` is non-negotiable for any modern JavaScript developer. It is the fundamental skill for creating scalable, maintainable applications.

JavaScript Modules Glossary

Module
A JavaScript file that has its own private scope and can choose what code to share (`export`) and what code to consume (`import`).
import
The keyword used to bring exported functionality from another module into the current module's scope.
export
The keyword used to make variables, functions, or classes in the current module available to other modules that `import` it.
Named Export
A way to export multiple values from a single file. They must be imported using the exact same name inside curly braces: import { value } from './module.js';
Default Export
A way to export a single primary value from a file. There can only be one per module. It can be imported with any name: import MyValue from './module.js';
Module Specifier
The string that specifies the location of the module, e.g., `'./utils.js'` (a local file) or `'react'` (a package).