Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 7

Module Organization with Import and Export

Recommended resources

Welcome to the final lesson of our "JavaScript Essentials for React" module! Over the last several lessons, you've built a solid foundation in the modern JavaScript syntax that is crucial for building React applications. You've mastered everything from declaring variables and writing arrow functions to transforming data and crafting dynamic strings.

Today, we will address the final, critical piece of this puzzle: how to organize your code. As applications grow, putting all your code in a single file becomes unmanageable. The solution is to break it into smaller, self-contained, and reusable pieces called modules. This lesson will teach you how to use import and export statements to share code between these files, a fundamental practice in all modern web development and the very backbone of a React project's structure.

Why Bother with Modules?

Imagine trying to build a complex machine where every single gear, wire, and screw was piled together in one giant box. It would be a nightmare to find anything or understand how the parts connect. Early JavaScript projects often felt like this.

Modules allow us to create separate files for different pieces of functionality. This has several key benefits:

  • Organization: Each file has a clear purpose (e.g., a file for utility functions, another for a specific UI component).
  • Reusability: A function or class written in one module can be easily used in many other parts of your application.
  • Maintainability: When you need to fix a bug or update a feature, you know exactly which file to edit, without risking breaking unrelated code.
  • Scope Control: Variables and functions defined in a module are private to that module by default. They don't "pollute" the global scope and cause naming conflicts, which is a common source of bugs in older JavaScript code.

The freeCodeCamp article below gives a great high-level introduction to this concept.

The JavaScript Modules Handbook – Complete Guide to ...

This section explains what a JavaScript module is and the problems it solves in modern development.

Read the first two sections, "What Exactly Is a JavaScript Module?" and "Why Use Modules?". This will give you the conceptual "why" before we dive into the syntax.


The Core Syntax: export and import

To make modules work, we need two keywords: export to make code available to other files, and import to bring that code into the file where we need it.

There are two main strategies for exporting code: named exports and default exports. Most projects use a combination of both.

1. Named Exports

Named exports are used to export multiple, specific values from a single file. Think of this as offering a public menu of several items that other files can choose from.

You can export items as you declare them:

// in file: mathUtils.js
export const pi = 3.14159;

export const add = (a, b) => a + b;

export const subtract = (a, b) => a - b;

Or you can export them all at once at the end of the file, which some developers find cleaner:

// in file: mathUtils.js
const pi = 3.14159;
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

export { pi, add, subtract };

To import these, you must use curly braces {} and the exact same names:

// in file: main.js
import { pi, add } from './mathUtils.js';

console.log(`The value of pi is ${pi}`);
console.log(`2 + 3 = ${add(2, 3)}`);

A key feature of named imports is the ability to rename them using the as keyword to avoid naming conflicts.

// in file: main.js
import { add as sum } from './mathUtils.js';

console.log(`2 + 3 = ${sum(2, 3)}`); // 'add' is now available as 'sum'

2. Default Exports

A default export is used to export a single, primary value from a file. Each file can have at most one default export. This is typically used for the "main thing" the file provides, like a React component or a class.

// in file: User.js
class User {
  constructor(name) {
    this.name = name;
  }
}

export default User;

When you import a default export, you do not use curly braces, and you can give it any name you like. The name doesn't have to match the original.

// in file: main.js
import MyUserClass from './User.js'; // We can name it whatever we want

const user = new MyUserClass('Alex');
console.log(user.name); // 'Alex'

The React Way: Default vs. Named Exports

The official React documentation provides an excellent guide on this topic, framed in the context of exporting and importing components, which is exactly how you'll be using modules in React.

Importing and Exporting Components

This guide from the React team clearly explains the difference between default and named exports and the conventions for using them.

Read through the following sections: Deep Dive: Default vs named exports: This section provides a fantastic side-by-side comparison and a summary table. Pay close attention to the syntax differences in the table. Exporting and importing multiple components from the same file: This section shows you how to combine default and named exports in a single file, a very common pattern.

The general convention in the React world is:

  • Use export default for the main component in a file.
  • Use export for any helper functions or related smaller components in the same file.

Visualizing the Syntax

To help you remember the different syntaxes, here is a handy cheatsheet that summarizes the patterns for default, named, and renamed imports/exports.

This cheatsheet provides a quick visual reference for the different JavaScript module import and export syntaxes.

Let's look at another practical example that brings these ideas together across multiple files.

This diagram illustrates how different export types (default, named) from `person.js` and `info.js` are imported into `index.js`.

In this diagram, notice:

  • person.js has a single export default. It can be imported as person or renamed to prs with no special syntax.
  • info.js has both a default export (position) and two named exports (age, sex).
  • In index.js, the named export sex is imported using curly braces: import { sex } from ....
  • The named export age is imported and renamed at the same time: import { age as ag } from ....
  • You can also import all named exports from a file into a single object using import * as all from .... You would then access them like all.sex and all.age.

The video below from Dave Gray walks through these concepts with clear, step-by-step examples of creating and using modules.

Javascript Modules | Export Import Syntax for ES6 Modules

This video provides practical demonstrations of creating, exporting from, and importing into JavaScript modules.

Please watch the following segments: Creating a Module: First, watch how he creates functions in a separate file and exports them using both default and named export syntax. Importing Code: Next, see how he imports these functions into the main file, including renaming an import with as. Class Example: Finally, watch the example where he exports and imports a JavaScript class, which is very similar to how you'll work with React components.


A Crucial Final Step: Making it Work in the Browser

There's one last detail. To tell the browser that your JavaScript file uses this module system, you must add type="module" to your <script> tag in your HTML file.

<!-- This script will be treated as a module -->
<script type="module" src="main.js"></script>

When you use type="module", the script is automatically "deferred," meaning the browser will load the HTML first before executing the script. This prevents errors and is the modern standard. The Web Dev Simplified video highlights this simple but essential step.

JavaScript ES6 Modules

This short clip explains the one line of HTML you need to enable modules.

Watch the segment from this point, where he explains why the import statement initially fails and how adding type="module" to the script tag fixes it.


Key Takeaways

This lesson completes your essential JavaScript toolkit for React. You now have the knowledge not only to write modern JS syntax but also to structure it in a clean, professional way.

  • Modules help organize code into separate, reusable files.
  • The export keyword makes variables, functions, or classes available to other modules.
  • A file can have many named exports (export const myVar = ...), which must be imported with matching names in curly braces (import { myVar } from ...).
  • A file can have only one default export (export default myVar), which can be imported with any name and no curly braces (import myCustomName from ...).
  • To enable modules in a browser, you must add type="module" to your <script> tag in the HTML.

Next Steps

Congratulations! You have successfully completed the first module, "JavaScript Essentials for React." You now possess the foundational JavaScript knowledge required to start building with React.

In the next module, "UI Fundamentals with HTML & CSS," we will shift gears. You'll learn how to create the structure of a web page using HTML and then apply styling with CSS. This will build your skills in creating the visual elements that your React code will eventually bring to life.