Popular Searches
Popular Course Categories
Popular Courses

Modules

28 mins Modern JavaScript (ES6+)

Modules in React JS

Course: React JS Training

Topic: Modules

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why Modules Matter in Modern JavaScript

Imagine writing an entire application in one giant JavaScript file. Every variable lives in the same shared space, one mistake breaks everything, and finding a single function among thousands of lines becomes a nightmare. Early web development worked exactly like this: developers stacked many <script> tags on a page and hoped the files did not clash with each other.

Modules solve this problem. A module is a file that keeps its own private space and deliberately shares only what it chooses to share. This idea is so central to modern development that every React project you will ever open is built from modules. When you write import React from "react", you are using the exact feature taught on this page. Understanding modules is therefore not optional preparation for React training — it is the daily grammar of the work.

By the end of this page you will be able to split code into files, share functions and values between them, and organise a small project the way professional teams do.

2. What Is a Module?

In simple words, a module is a JavaScript file that has its own private scope and can explicitly share pieces of itself with other files using export, and use pieces of other files using import.

Three ideas sit behind this definition:

  • One file, one purpose. A module usually contains related code — all price calculations, all string helpers, one React component — so the file name tells you what is inside.
  • Privacy by default. Variables, functions and classes inside a module are invisible to other files unless you explicitly export them. Nothing leaks by accident.
  • Explicit connections. Every dependency is written at the top of the file as an import. Anyone reading the file can see exactly what it needs.

Compare that with the old way of loading several scripts on one page:

AspectOld style: many script tagsModern style: modules
ScopeTop-level variables are shared globally across all filesEach file has its own private scope
SharingDepends on the order the script tags are writtenExplicit import and export statements
Finding dependenciesYou must read the HTML to guess what a file needsStated at the top of every file
Name clashesCommon and hard to debugPrevented by private scope and renaming
Reusing codeCopy and paste between projectsMove the file, import it anywhere

3. Key Terms You Will See Everywhere

These words appear in every documentation page, tutorial and codebase that uses modules. Learn them now and everything later becomes easier to read.

  • Module: a JavaScript file treated as its own unit of code with a private scope.
  • Export: a statement that makes something inside a module available to other modules. Exported items are the module's public surface.
  • Import: a statement that brings exported items from another module into the current file.
  • Named export: an export with a specific name, such as export const total = 100. A file can have many named exports, and importers must use the same name.
  • Default export: the single main export of a file, written as export default. A file can have only one, and the importer may call it any name.
  • Module specifier: the path or name after from in an import, such as "./math.js".
  • Entry file: the first module the browser or tool loads, from which all other modules are reached.
  • Dependency graph: the web of imports connecting every module of a project. Tools read this graph to bundle, optimise and load your code.
A helpful mental picture: a module is a shop. export is the shop window — it shows only what the shop wants to sell. import is a customer walking in and asking for a specific item by name.

4. The Two Sides of the Syntax: export

There are two positions where export can appear: next to the declaration itself, or on its own line at the bottom of the file. Both are equally valid; teams simply pick one style and stay consistent.

Inline named exports

// math.js
export const TAX_RATE = 0.18;

export function addTax(amount) {
  return amount * (1 + TAX_RATE);
}

export class Invoice {
  constructor(customer) {
    this.customer = customer;
    this.items = [];
  }
}

Exports listed at the bottom

// math.js
const TAX_RATE = 0.18;

function addTax(amount) {
  return amount * (1 + TAX_RATE);
}

class Invoice {
  constructor(customer) {
    this.customer = customer;
    this.items = [];
  }
}

export { TAX_RATE, addTax, Invoice };

Notice the curly braces in the bottom style. export { addTax } is not an object — it is a list of names to expose. A common beginner mistake is writing export = addTax or wrapping names in quotes; neither is valid.

The default export

// greeting.js
export default function greet(name) {
  return `Hello, ${name}!`;
}

The words export default go in front of the one thing that represents the file. A file may combine one default export with any number of named exports.

5. The Two Sides of the Syntax: import

Imports mirror the exports of the file you are reading from. There are four shapes to learn, and together they cover almost every import you will ever write.

Import shapeUse it whenExample
import { name } from "..."The file uses named exportsimport { addTax } from "./math.js"
import anything from "..."The file has a default exportimport greet from "./greeting.js"
import * as ns from "..."You want everything under one namespaceimport * as math from "./math.js"
import "..."You only want the file's side effects, no valuesimport "./setup.js"

Two small but important details:

  • Renaming during import uses the keyword as: import { addTax as withTax } from "./math.js". After this line, the current file uses withTax.
  • The module specifier must normally be a path starting with ./, ../ or / for your own files, or a package name such as "react" for installed libraries. Browsers do not guess file names or extensions.

6. How a Module Project Works, Step by Step

Follow this workflow whenever you split code into modules. It is the same workflow used in every React project, only at a smaller scale.

  1. Create the files. Give each file a name that describes its job, such as cart.js or format.js.
  2. Decide the public surface. Ask: what does the rest of the program need from this file? Export only that. Everything else stays private.
  3. Write the imports first. At the top of each file, list what it needs from other modules. Reading a file should start with its dependencies.
  4. Load the entry file in the browser with type="module" so the browser treats it as a module and follows its imports automatically.
  5. Trace the dependency graph. The browser starts at the entry file, reads each import, fetches that file, reads its imports, and so on until everything needed is loaded.

The HTML for a module project looks like this:

<!DOCTYPE html>
<html>
<head>
  <title>Shop demo</title>
</head>
<body>
  <script type="module" src="main.js"></script>
</body>
</html>

The attribute type="module" is essential. Without it, the browser treats main.js as a classic script and the words import and export cause a syntax error. Modules are also automatically loaded in a deferred way, which means the browser waits until the HTML is parsed before running them — so the old advice about placing scripts at the bottom of the page is no longer needed for module scripts.

Modules must be served over a server (even a simple local one), not opened directly as files from the disk, because the browser's security rules for modules restrict file-based loading. In practice, every React project runs through a development server anyway, so this rule is handled for you.

7. Worked Example: A First Two-File Project

Start with the smallest possible module project: one file does arithmetic, the other uses it.

// math.js
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

export { add, multiply };
// main.js
import { add, multiply } from "./math.js";

console.log(add(4, 6));        // 10
console.log(multiply(4, 6));   // 24

What happens at run time:

  1. The browser loads main.js because of the type="module" script tag.
  2. It sees the import of ./math.js and loads that file too.
  3. Inside math.js, the export statement publishes add and multiply.
  4. main.js binds those names locally and runs the console statements.

If math.js also contained a private helper, the two files could never see or clash with it:

// math.js
let callCount = 0;   // private: not exported, invisible outside

function add(a, b) {
  callCount = callCount + 1;
  return a + b;
}

export { add };

callCount is module-private. No other file can read it, overwrite it or even know it exists. This privacy is what keeps large codebases sane.

8. Worked Example: Renaming and Avoiding Clashes

Two files may both export a function called format. Renaming at import time resolves the clash without touching either file.

// money.js
export function format(value) {
  return "Rs " + value.toFixed(2);
}
// dates.js
export function format(value) {
  const d = new Date(value);
  return d.toLocaleDateString("en-IN");
}
// main.js
import { format as formatMoney } from "./money.js";
import { format as formatDate } from "./dates.js";

console.log(formatMoney(1250));          // Rs 1250.00
console.log(formatDate("2026-05-12"));   // 12/5/2026

You can also rename at the export site with export { format as formatMoney }, but renaming during import is more common because it lets each importing file choose names that read naturally in its own context.

9. Worked Example: Default Export Mixed with Named Exports

A realistic pattern: one file represents a single main thing (the default export) plus a few supporting utilities (named exports). This is exactly how React components are typically written — the component is the default export, small helpers are named.

// discount.js
const MEMBER_DISCOUNT = 0.15;
const FESTIVE_DISCOUNT = 0.10;

export default function applyDiscount(price, isMember) {
  const rate = isMember ? MEMBER_DISCOUNT : FESTIVE_DISCOUNT;
  return price - price * rate;
}

export function isMember(user) {
  return user.plan === "member";
}
// main.js
import applyDiscount, { isMember } from "./discount.js";

const user = { name: "Asha", plan: "member" };

if (isMember(user)) {
  console.log(applyDiscount(2000, true));   // 1700
} else {
  console.log(applyDiscount(2000, false));  // 1800
}

Read the import line carefully: applyDiscount outside the braces receives the default export, while isMember inside the braces receives a named export. Both arrive in one statement. Note also that the default import name is chosen freely by the importing file — import applyBestDiscount from "./discount.js" would work identically, though choosing a clear name is better style.

10. Worked Example: Importing Everything as a Namespace

When a module has many exports and you use most of them, a namespace import keeps the import line short:

// stats.js
export const mean = (nums) => nums.reduce((a, b) => a + b, 0) / nums.length;

export const max = (nums) => Math.max(...nums);

export const min = (nums) => Math.min(...nums);
// main.js
import * as stats from "./stats.js";

const scores = [72, 88, 95, 61];

console.log(stats.mean(scores));  // 79
console.log(stats.max(scores));   // 95
console.log(stats.min(scores));   // 61

The asterisk means "all named exports", and as stats puts them into one object. Default exports are not included under their own name in a namespace import; they appear under the special key default, which is one reason namespace imports are usually reserved for modules with only named exports.

A useful side effect: because stats is an object, you can loop over its methods or pass the whole bundle around as a value.

11. Worked Example: A Realistic Mini Shop Project

Now combine everything into a small but realistic structure with four modules, each with a single purpose.

// products.js
const products = [
  { id: 1, name: "Keyboard", price: 1500 },
  { id: 2, name: "Mouse", price: 700 },
  { id: 3, name: "Monitor", price: 9500 }
];

export function findProduct(id) {
  return products.find((p) => p.id === id);
}

export function allProducts() {
  return products;
}
// cart.js
import { findProduct } from "./products.js";

const items = [];

export function addToCart(productId, qty) {
  const product = findProduct(productId);
  if (!product) {
    throw new Error("Unknown product id: " + productId);
  }
  items.push({ ...product, qty });
}

export function cartTotal() {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
// format.js
export function inRupees(amount) {
  return "Rs " + amount.toLocaleString("en-IN");
}
// main.js
import { addToCart, cartTotal } from "./cart.js";
import { inRupees } from "./format.js";

addToCart(1, 2);   // two keyboards
addToCart(2, 1);   // one mouse

console.log(inRupees(cartTotal()));   // Rs 3,700.00

Study what each module chose to expose:

  • products.js keeps the product array private and exposes only two functions. No other file can accidentally overwrite the product list.
  • cart.js imports what it needs, keeps the cart contents private, and exposes only the two operations the rest of the app requires.
  • format.js is a pure utility module with no state at all.
  • main.js is the entry file: it contains no business logic, only the flow of the program.

This separation is precisely the habit React training builds on. In a React application, main.js becomes the entry point that renders the app, each component lives in its own module, and utility modules like format.js are imported wherever needed.

12. Re-Exporting and Barrel Files

As a project grows, import paths get long and repetitive. A common professional pattern is a barrel file: a small module whose only job is to re-export the contents of several other modules, so that importing files need one short path.

// utils/index.js  (the barrel file)
export { inRupees } from "./format.js";
export { addToCart, cartTotal } from "./cart.js";
export { findProduct, allProducts } from "./products.js";
// main.js — now a single import line
import { addToCart, cartTotal, inRupees } from "./utils/index.js";

The syntax export { name } from "./file.js" both imports and re-exports in one statement, without the re-exported names becoming available inside the barrel file itself. A barrel can also re-export a default export under a chosen name:

export { default as applyDiscount } from "./discount.js";

Barrel files keep import sections tidy in medium and large codebases, and you will meet them constantly in React projects, where a folder of components often has an index.js barrel.

13. Dynamic Import with import()

All the imports shown so far are static: they must be at the top level of the file, and the browser loads them when the module loads. Sometimes you want code only when something happens — for example, loading a heavy chart library only after the user clicks "Show report". The dynamic form import() does this: it is called like a function and returns a Promise that resolves to the module.

// report.js
export default function buildReport() {
  return "Sales report data";
}
// main.js
showButton.addEventListener("click", async () => {
  const module = await import("./report.js");
  console.log(module.default());   // Sales report data
});

Key differences between the two forms:

FeatureStatic importDynamic import()
PlacementTop level of the file onlyAnywhere code runs: inside functions, event handlers, conditions
What it returnsBindings available immediatelyA Promise resolving to the module
Loading timeLoaded with the module graph at startFetched only when the call runs
Typical useCore dependencies used on every pageLarge or rarely used features

Dynamic import connects directly to the Promises and async/await topics covered on their own pages in this module, and it is the mechanism behind code-splitting in modern React applications — loading parts of an app only when the user actually navigates to them.

14. How Modules Behave: Rules Worth Remembering

A few behaviours of the module system surprise beginners. Knowing them now prevents hours of confusion later.

  • Modules run once. If two different files import the same module, the module's code executes a single time, and both importers share the same values. This makes an imported module a natural place for shared state.
  • Imports are read-only views. You cannot assign to an imported binding. If a module exports let count, another file cannot write count = 5; it can only read the current value. Changes made inside the exporting module are visible to importers.
  • Imports are hoisted. Import statements are processed before the rest of the file runs, so you may call an imported function above the import line and it still works — though keeping imports at the top is the clear, expected style.
  • Export statements must be top-level. You cannot export from inside a function or an if block. Conditional sharing is achieved by exporting a function whose behaviour changes, not by conditional exports.
  • Specifiers are exact. Browsers require the correct relative path and file extension for your own modules; there is no automatic guessing. Bundlers used in React projects add conveniences on top of this, but the underlying rule stays the same.

Here is the "runs once" behaviour demonstrated:

// counter.js
export let count = 0;

export function increment() {
  count = count + 1;
}
// a.js
import { increment } from "./counter.js";
increment();
// b.js
import { increment, count } from "./counter.js";
increment();
console.log(count);   // 2 — same shared module, not two copies

Both a.js and b.js act on the one counter.js module instance, so the count reaches 2. This shared-instance behaviour is the same idea React relies on when many components import one shared utility module.

15. Advanced Patterns in Real Projects

Once the basics are solid, a few patterns appear again and again in professional codebases. Learning to recognise them makes reading real projects far easier.

Configuration modules

Instead of scattering settings across the codebase, teams keep them in one module. Because a module runs once and is shared by every importer, it acts as a single source of truth.

// config.js
export const APP_NAME = "ShopSmart";
export const CURRENCY = "INR";
export const API_BASE = "https://api.example.com";
export const MAX_CART_ITEMS = 20;
// anywhere in the app
import { API_BASE, MAX_CART_ITEMS } from "./config.js";

fetch(`${API_BASE}/products`)
  .then((res) => res.json())
  .then((data) => console.log(data));

Side-effect modules

Some modules exist only to perform an action when they load, with no exports at all. They are imported for their effect:

// register-warnings.js
window.addEventListener("beforeunload", (event) => {
  console.log("Remember to save your work.");
});
// main.js
import "./register-warnings.js";

Use this sparingly and name the file clearly, because a bare import hides what it does. In React projects you will see this pattern for global CSS files, where a line like import "./index.css" applies styles to the whole app.

Private helpers with a public API

A well-designed module exposes verbs, not internals. The mini shop from earlier is a model: cart.js never exports the items array, only addToCart and cartTotal. This lets you change the internal storage later — from an array to a Map, for example — without breaking a single importing file. That freedom to refactor is the real payoff of module privacy.

16. Common Mistakes and the Correct Way

These errors account for most module problems beginners face. Each one is shown with the broken version and the fix.

Forgetting type="module" in the script tag

<!-- Wrong: import causes a syntax error -->
<script src="main.js"></script>

<!-- Correct -->
<script type="module" src="main.js"></script>

Missing the ./ in your own file paths

import { add } from "math.js";      // Wrong: treated as a package name
import { add } from "./math.js";    // Correct: relative path

Browsers read a specifier without ./, ../ or / as the name of an installed package, then fail because no such package exists.

Wrapping named imports in the wrong braces

import add from "./math.js";          // imports the DEFAULT export
import { add } from "./math.js";      // imports the NAMED export "add"

If math.js has no default export, the first line gives you undefined — a silent bug that only shows up later when add(2, 3) crashes. When something imported is unexpectedly undefined, check whether the file actually exports it by the name you used.

Trying to export from inside a function

function setup() {
  export const helper = () => {};   // SyntaxError
}

Exports must sit at the top level of the file. The correct approach is to export the function that controls the behaviour:

export const helper = () => {};

export function setup() {
  helper();
}

Assigning to an imported binding

import { TAX_RATE } from "./config.js";
TAX_RATE = 0.05;   // TypeError: assignment to constant or read-only import

Imports are read-only. If you need a different value, compute a new local variable:

const discountedRate = TAX_RATE * 0.5;

Circular imports between two files

If a.js imports from b.js and b.js imports from a.js, the files form a circle. The module system survives it, but one of the files may see unfinished values during startup, producing undefined at surprising moments. The fix is to extract the shared code into a third module that both files import:

// shared.js — the common ground
export function log(message) {
  console.log("[app] " + message);
}
// a.js
import { log } from "./shared.js";
export function start() {
  log("starting");
}
// b.js
import { log } from "./shared.js";
export function stop() {
  log("stopping");
}

As a rule, aim for one-directional dependencies: utility modules at the bottom, feature modules above them, and the entry file at the top.

17. Best Practices for Working with Modules

Adopt these habits from your first project. They cost nothing now and pay off for years.

  • One module, one job. If a file's name needs the word "and", it probably wants to be two files. Small, single-purpose modules are easier to test, reuse and read.
  • Keep imports at the top. Even though imports are hoisted, placing them first shows a reader the file's dependencies immediately.
  • Prefer named exports for utilities. A file with several helpers should export them by name. Reserve export default for the case where the file represents exactly one thing, such as a React component.
  • Export the minimum. Every export is a promise you must keep. Anything not exported can be changed freely later.
  • Use consistent naming. Files in lower-case with hyphens, such as price-utils.js, avoid problems on systems where file names are case-sensitive.
  • Do not deep-import past a barrel. Once a folder offers an index.js barrel, import from the folder rather than reaching into its internal files, so the internal structure stays free to change.
  • Let bundlers do the optimising. In real React projects, tools read your import graph and bundle, split and optimise the code automatically. Write clear modules; the tooling handles the rest.

These habits match the broader advice given for modern React development: keep units small and single-purpose, and let the tooling — including the React Compiler's automatic optimisations — handle performance work that used to be done by hand.

18. Practical Project: A Marksheet Calculator Built from Modules

Build a small marksheet application with four modules and one HTML page. It takes marks for three subjects, computes the total, percentage and grade, and prints a formatted result. Follow the steps in order.

Step 1: Create the folder structure

marksheet/
  index.html
  js/
    main.js
    marks.js
    grade.js
    format.js

Step 2: Write the data module

marks.js holds the subject marks and exposes two operations. The array itself stays private.

// js/marks.js
const marks = [
  { subject: "Mathematics", score: 82 },
  { subject: "Science", score: 91 },
  { subject: "English", score: 74 }
];

export function total() {
  return marks.reduce((sum, m) => sum + m.score, 0);
}

export function count() {
  return marks.length;
}

Step 3: Write the logic module

grade.js turns numbers into a grade. It imports nothing — it is a pure logic module.

// js/grade.js
export function percentage(totalMarks, subjects) {
  return (totalMarks / (subjects * 100)) * 100;
}

export function grade(percent) {
  if (percent >= 90) return "A+";
  if (percent >= 75) return "A";
  if (percent >= 60) return "B";
  if (percent >= 40) return "C";
  return "Fail";
}

Step 4: Write the formatting module

// js/format.js
export function line(label, value) {
  return label.padEnd(14, " ") + ": " + value;
}

Step 5: Write the entry module

main.js imports from all three modules and composes the flow. Notice how each import names only what is used.

// js/main.js
import { total, count } from "./marks.js";
import { percentage, grade } from "./grade.js";
import { line } from "./format.js";

const totalMarks = total();
const subjects = count();
const percent = percentage(totalMarks, subjects);

console.log("------ Marksheet ------");
console.log(line("Total", totalMarks + " / " + subjects * 100));
console.log(line("Percentage", percent.toFixed(2) + "%"));
console.log(line("Grade", grade(percent)));

Step 6: Load it in the browser

<!DOCTYPE html>
<html>
<head>
  <title>Marksheet</title>
</head>
<body>
  <script type="module" src="js/main.js"></script>
</body>
</html>

Expected output

------ Marksheet ------
Total         : 247 / 300
Percentage    : 82.33%
Grade         : A

Step 7: Extend it

Good next moves that deepen the same lesson:

  1. Add a named export highest() to marks.js that returns the subject with the top score, and print it from main.js.
  2. Create a barrel file js/index.js that re-exports all three modules, then shorten the imports in main.js to one line.
  3. Move the grade thresholds into a config.js module so grade.js imports them instead of hard-coding them.

This project mirrors the structure of every React application: a data module, pure logic modules, a formatting utility and an entry file that wires everything together.

19. Practice Exercises

  1. Create a module strings.js with named exports toUpperCase and reverse, then import and use both in main.js.
  2. Write a module with one default export (a function that greets a user) and one named export (a constant). Import both in a single statement.
  3. Two modules both export a function called validate. Import both into one file without a name clash.
  4. Build a namespace import over a module with at least three named exports and call each one through the namespace object.
  5. Create a barrel file for a folder of three utility modules and rewrite an importing file to use it.
  6. Convert one static import into a dynamic import() triggered by a button click, and log a value from the loaded module.
  7. Demonstrate the "modules run once" rule: import the same module from two files, call its increment function from both, and show the shared result.
  8. Find and fix the bug: a file writes import myHelper from "./utils.js" but utils.js only has named exports. Explain why the value is undefined and write the corrected import.

20. Interview Questions and Answers

What is a JavaScript module and why does it exist?

A module is a file with its own private scope that explicitly shares code through export and consumes other files' code through import. It exists to prevent global name clashes, make dependencies visible, and let applications be split into small, reusable, testable files.

What is the difference between named and default exports?

A named export exposes a value under a specific name; a file can have many, and importers must use the same name inside braces. A default export is the single main value of a file; there can be only one per file, and the importer may call it any name without braces. Named exports suit utilities; default export suits files that represent one main thing, like a React component.

How do you import a default export and a named export together?

In one statement, with the default name outside the braces: import applyDiscount, { isMember } from "./discount.js". The name before the comma binds the default export; the names inside the braces bind named exports.

What does import * as ns from "./file.js" do?

It imports all named exports of the file into a single namespace object. You then access each export as a property, such as ns.mean(scores). It is useful when a module has many exports you use most of.

Are imported bindings writable?

No. Import statements create read-only bindings. You cannot assign to an imported name; you can only read its current value. If the exporting module changes an exported let variable, importers see the new value, but they cannot change it themselves.

How many times does an imported module's code run?

Once, no matter how many files import it. The module is evaluated a single time and every importer shares the same instance and values. This makes modules a natural place for shared configuration or state.

Why is type="module" required on the script tag?

Without it the browser treats the file as a classic script, where import and export are syntax errors. The attribute switches on module behaviour: private scope per file, import resolution, deferred execution and strict mode.

What is a barrel file and when is it useful?

A barrel is a module, usually an index.js, whose only job is re-exporting the contents of several files using export { name } from "./file.js". It shortens import paths and hides internal file structure, which is common in React projects where a components folder exposes one clean entry point.

What is the difference between static import and dynamic import()?

Static import is written at the top level, is resolved when the module loads, and returns bindings directly. Dynamic import() can be called anywhere code runs, returns a Promise that resolves to the module, and fetches the file only when the call executes — which is the basis of loading large features on demand.

What problems do circular imports cause and how do you fix them?

When two modules import each other, one may read values from the other before it has finished evaluating, producing undefined at run time. The standard fix is to extract the shared code into a third module that both import, restoring one-directional dependencies.

Why do modules matter for React development?

Every React application is a graph of modules: the entry file imports the root component, each component lives in its own module, and utilities are shared through imports. Features like code-splitting rely on dynamic import(), and bundlers optimise the app by analysing the import graph. You cannot read or write a real React codebase without this syntax.

Can you export from inside a function or an if block?

No. export must appear at the top level of a module. To share behaviour conditionally, export a function whose internal logic changes, or export an object whose properties you set at run time.

21. Quick Revision Checklist

  • I can define a module: a file with a private scope that shares code via export and consumes code via import.
  • I can write inline named exports and exports listed at the bottom with export { a, b }.
  • I know a file has at most one default export and importers may rename it freely.
  • I can import named exports with braces, a default export without braces, both in one line, and everything as a namespace with * as.
  • I rename with as during import to avoid clashes.
  • I always load module code with <script type="module"> and use ./ paths for my own files.
  • I know modules run once, imports are read-only, imports are hoisted, and exports must be top-level.
  • I can build a barrel file with export { name } from "./file.js".
  • I can use dynamic import() inside an event handler and await the Promise it returns.
  • I can split a small application into data, logic, format and entry modules, and explain what each one keeps private.

22. Official Documentation and Further Reading

These resources from the course reading list connect modules to the React work ahead:

Conclusion

Modules turn JavaScript from a pile of scripts into an organised application. With export you decide what a file shares; with import you state exactly what a file needs; and the module system quietly enforces privacy, single evaluation and clear dependencies. You have practised named and default exports, renaming, namespace imports, barrel files and dynamic loading, and you have built a complete multi-module project by hand.

Every concept from here on in the course assumes this skill. The React components you write will be modules; the hooks, utilities and configuration they use will arrive through imports. Keep the habits from this page — one job per file, minimal exports, imports at the top — and the step into React development will feel less like learning a new language and more like applying the one you already know.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp