Import and Export
By Syncfusion®, Inc. · Last updated
What a module is and why module scope matters, named and default exports, importing with as and import * as, type="module" and file paths, common module errors, dynamic import(), and CommonJS.
What Is a Module?
Module = a JavaScript file that keeps its names private unless it chooses to share them.
exportshares a value from a file.importbrings a shared value into another file.- Everything else in the file stays inside it.
Simple lesson: nothing leaves a module unless it is exported, and nothing enters unless it is imported.
A Real-World Example
A shop project has prices.js (tax and formatting), cart.js (the cart) and main.js (the page).
main.js writes import { formatPrice } from "./prices.js" and uses it.
prices.js keeps its TAX_RATE private, so no other file can change it by accident.
prices.js const TAX_RATE (private) export formatPrice
main.js import { formatPrice }
formatPrice
Only exported names travel between files.
Two kinds of boxes here. Project boxes have several real files (main.js, prices.js...) in an explorer; edit any file and Run. Single boxes run as a function body, so they build modules from text with URL.createObjectURL(), a real browser module loader. Some single boxes fail on purpose.
What You Will Learn
- What modules are, and module scope versus global scope.
- Named exports, default exports and export lists.
- Named, default, renamed (
as) and namespace (* as) imports. type="module", path rules and common module errors.- Dynamic
import(), and CommonJS (require) versus ES modules.
Introduction to JavaScript modules
Before modules, every script shared one space for names: two files declaring total overwrote each other. Modules give each file its own space.
What is a module?
A file whose top-level names are private. addTax is exported and usable; TAX_RATE is not, so outside it is undefined.
Build a small cart module and use what it exports
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const cartUrl = moduleUrl(`
const TAX_RATE = 0.18;
export function addTax(price) {
return price + price * TAX_RATE;
}
`);
const cart = await import(cartUrl);
console.log("addTax(1000):", cart.addTax(1000));
console.log("TAX_RATE from outside:", cart.TAX_RATE);
Expected output:
addTax(1000): 1180
TAX_RATE from outside: undefined
Why modules are needed
- Name clashes: a name belongs only to its own file.
- Hidden needs:
importlines say exactly what a file depends on. - Large files: split a program into small files, each with one job.
shop/
├── index.html loads main.js as a module
├── main.js imports from the files below and starts the page
├── cart.js exports addToCart, removeFromCart
├── prices.js exports addTax, formatPrice
└── api.js exports loadProducts
Here is that idea as a real project box. Open each file in the explorer:
A shop split into three modules
// @file: main.js
import { addToCart, cartTotal } from "./cart.js";
import { formatPrice } from "./prices.js";
addToCart({ name: "Notebook", price: 60 });
addToCart({ name: "Lunch box", price: 349 });
console.log("Total with tax:", formatPrice(cartTotal()));
// @file: cart.js
import { addTax } from "./prices.js";
const items = [];
export function addToCart(product) {
items.push(product);
}
export function cartTotal() {
return addTax(items.reduce((sum, item) => sum + item.price, 0));
}
// @file: prices.js
const TAX_RATE = 0.18;
export function addTax(price) {
return price + price * TAX_RATE;
}
export function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
items and TAX_RATE are private. main.js can only use what was exported.
Module scope vs global scope
Scope = where a name can be used. Global scope = one space shared by every classic script. Module scope = private to one file. Even a module's var stays inside:
A module's top-level names stay inside the module
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const settingsUrl = moduleUrl(`
var region = "IN";
const currency = "INR";
export const label = region + " prices in " + currency;
`);
const settings = await import(settingsUrl);
console.log("Exported label:", settings.label);
console.log("Is region global? ", "region" in globalThis);
console.log("Is currency global?", "currency" in globalThis);
Expected output:
Exported label: IN prices in INR
Is region global? false
Is currency global? false
// A classic <script>: a top-level var joins the global object.
var region = "IN";
console.log(window.region); // "IN"
// A module: it does not.
var region = "IN";
console.log(window.region); // undefined
To share a value, export it and import it. Do not attach it to window.
Exporting from modules
Export = mark a value as shareable. Two kinds: named and default.
Named export
Put export in front of a declaration. A file can have many. Importers must use the exact names.
// prices.js
export const TAX_RATE = 0.18;
export function addTax(price) {
return price + price * TAX_RATE;
}
export function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
Use named exports by default. The same name appears in both files, so editors can find every use.
Default export
export default marks the one main value of a file. The importer picks any name for it.
// formatPrice.js
export default function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
Why "default"? It is what you get when you import without asking for a name.
Export list at bottom of file
Declare normally, then list the exports at the end: export { a, b };. Same result; the public names are easy to see in one place.
// cart.js
const items = [];
function addToCart(product) {
items.push(product);
}
function cartCount() {
return items.length;
}
export { addToCart, cartCount };
Importing from modules
Import lines go at the top; the path in quotes names the file.
Importing named exports
Names go in { } and must match exactly.
// main.js
import { addTax, formatPrice } from "./prices.js";
console.log(formatPrice(addTax(1000))); // "₹1180.00"
One module imports named exports from another
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const pricesUrl = moduleUrl(`
export const TAX_RATE = 0.18;
export function addTax(price) {
return price + price * TAX_RATE;
}
export function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
`);
const mainUrl = moduleUrl(`
import { addTax, formatPrice } from "${pricesUrl}";
export const receipt = "Total: " + formatPrice(addTax(1000));
`);
const main = await import(mainUrl);
console.log(main.receipt);
Expected output:
Total: ₹1180.00
A name that does not exist stops the module from loading, with a clear message:
Asking for a name the module does not export
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const pricesUrl = moduleUrl(`export function addTax(price) { return price * 1.18; }`);
const mainUrl = moduleUrl(`import { addGst } from "${pricesUrl}";`);
try {
await import(mainUrl);
} catch (error) {
console.log(error.name + ":", error.message.replace(pricesUrl, "./prices.js"));
}
Expected output:
SyntaxError: The requested module './prices.js' does not provide an export named 'addGst'
Importing default exports
No braces, any name you like. A file can mix both: import showPrice, { CURRENCY } from "./formatPrice.js".
// main.js
import formatPrice from "./formatPrice.js";
import showPrice from "./formatPrice.js"; // also works: same function, different name
Import a default export under a name you choose
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const formatUrl = moduleUrl(`
export default function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
export const CURRENCY = "INR";
`);
const mainUrl = moduleUrl(`
import showPrice, { CURRENCY } from "${formatUrl}";
export const line = showPrice(499) + " (" + CURRENCY + ")";
`);
console.log((await import(mainUrl)).line);
Expected output:
₹499.00 (INR)
Braces decide the kind. import { formatPrice } asks for a named export. If the file only has a default export, it fails with "does not provide an export named".
Renaming imports and exports (as)
as renames at the border: on an import to avoid a clash, on an export to give a public name.
// Renaming on the way in
import { addTax as addGst } from "./prices.js";
// Renaming on the way out
function calculateTotal(items) { /* ... */ }
export { calculateTotal as total };
Rename a clashing import, and rename an export
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const pricesUrl = moduleUrl(`
function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
export { formatPrice as format };
`);
const mainUrl = moduleUrl(`
import { format as formatRupees } from "${pricesUrl}";
function format(text) {
return text.toUpperCase();
}
export const heading = format("order summary") + ": " + formatRupees(250);
`);
console.log((await import(mainUrl)).heading);
Expected output:
ORDER SUMMARY: ₹250.00
Import everything (import * as)
Collects every export into one namespace object. A default export appears as .default.
import * as prices from "./prices.js";
prices.addTax(1000);
prices.formatPrice(1180);
Gather every export into one namespace object
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const pricesUrl = moduleUrl(`
export const TAX_RATE = 0.18;
export function addTax(price) {
return price + price * TAX_RATE;
}
export default "prices module";
`);
const mainUrl = moduleUrl(`
import * as prices from "${pricesUrl}";
export const names = Object.keys(prices);
export const total = prices.addTax(500);
export const title = prices.default;
`);
const main = await import(mainUrl);
console.log("Properties:", main.names);
console.log("addTax(500):", main.total);
console.log("default:", main.title);
Expected output:
Properties: [
"TAX_RATE",
"addTax",
"default"
]
addTax(500): 590
default: prices module
All import styles in one project box:
Named, default, renamed and namespace imports
// @file: main.js
import showPrice, { CURRENCY } from "./format.js";
import { addTax as addGst } from "./prices.js";
import * as prices from "./prices.js";
console.log(showPrice(addGst(500)), CURRENCY);
console.log("namespace keys:", Object.keys(prices).join(", "));
// @file: format.js
export const CURRENCY = "INR";
export default function formatPrice(amount) {
return "₹" + amount.toFixed(2);
}
// @file: prices.js
export const TAX_RATE = 0.18;
export function addTax(price) {
return price + price * TAX_RATE;
}
Try import { formatPrice } from "./format.js" in main.js and Run: the box shows the real error.
Working with module files
Script tag with type="module"
A plain <script> is a classic script: import/export are errors there. type="module" makes it a module. Only the entry file needs it.
<!-- A classic script: import and export are syntax errors here -->
<script src="main.js"></script>
<!-- A module: import and export work -->
<script type="module" src="main.js"></script>
Module scripts also wait for the HTML to load (like defer) and always run in strict mode.
Modules must be served by a web server. Opening index.html from disk (file://) blocks them.
Module file path rules (./, .js)
The path after from is the module specifier. In the browser:
- Start relative paths with
./(this folder) or../(one folder up). - Write the extension:
./prices.js, not./prices.
import { addTax } from "./prices.js"; // correct: same folder, with .js
import { loadProducts } from "../api/api.js"; // correct: one folder up, then into api/
import { addTax } from "./prices"; // wrong: no extension, the browser asks for a file called "prices"
A path with no ./, ../ or / is a bare specifier: a package name the browser cannot find without a build tool.
A bare specifier cannot be resolved in the browser
try {
await import("lodash");
} catch (error) {
console.log("Failed with a", error.name);
}
Expected output:
Failed with a TypeError
Common module errors and fixes
import in a file that is not a module:
An import statement outside a module
import { addTax } from "./prices.js";
console.log(addTax(1000));
export gives a different message for the same cause:
An export statement outside a module
export const TAX_RATE = 0.18;
| Error message | What it means | Fix |
|---|---|---|
Cannot use import statement outside a module | The file is loaded as a classic script | Add type="module" to the script tag |
Unexpected token 'export' | The same cause, reported for export | Add type="module" to the script tag |
Failed to resolve module specifier "prices" | The path has no ./ or ../, so it looks like a package name | Start the path with ./ or ../ |
A 404 (Not Found) error for prices in the console | The extension is missing, so the file is not found | Write the full name, ./prices.js |
does not provide an export named 'addGst' | The imported name does not match any export | Fix the spelling, or drop the braces for a default export |
require is not defined | CommonJS code is running where only ES modules work | Use import, as shown below |
Advanced module concepts
So far all imports were static: fixed at the top, loaded before any code runs.
Dynamic import()
import("./chart.js") loads a module while the program runs, only when needed: less code for visitors who never use it.
// Load the chart code only when the button is pressed
chartButton.addEventListener("click", async () => {
const { drawChart } = await import("./chart.js");
drawChart(salesData);
});
Load a coupon module only when a coupon is entered
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const couponsUrl = moduleUrl(`
console.log(" (coupons module is loading now)");
const codes = { WELCOME10: 0.1, FESTIVE20: 0.2 };
export function discountFor(code) {
return codes[code] ?? 0;
}
`);
async function checkout(total, code) {
if (!code) return total;
const { discountFor } = await import(couponsUrl);
return total - total * discountFor(code);
}
console.log("No coupon:", await checkout(1000, ""));
console.log("WELCOME10:", await checkout(1000, "WELCOME10"));
console.log("FESTIVE20:", await checkout(1000, "FESTIVE20"));
Expected output:
No coupon: 1000
(coupons module is loading now)
WELCOME10: 900
FESTIVE20: 800
Why "dynamic"? The decision to load happens at run time, and can depend on what the person does.
import() returns a promise
Loading takes time, so import() returns a promise for the namespace object. Use await or then(); a default export is .default.
import() hands back a promise for the namespace object
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
const greetUrl = moduleUrl(`
export default function greet(name) {
return "Welcome back, " + name + "!";
}
`);
const pending = import(greetUrl);
console.log("Is it a promise?", pending instanceof Promise);
pending.then((module) => {
console.log("With then():", module.default("Asha"));
});
const module = await pending;
console.log("With await: ", module.default("Ravi"));
try {
await import(moduleUrl("export const broken = ;"));
} catch (error) {
console.log("A broken module rejects with a", error.name);
}
Expected output:
Is it a promise? true
With then(): Welcome back, Asha!
With await: Welcome back, Ravi!
A broken module rejects with a SyntaxError
Destructure as it arrives: const { discountFor } = await import("./coupons.js"), or const { default: greet } = await import("./greet.js").
CommonJS (require, module.exports)
Node.js's older module system, still common in packages:
module.exports= what a file shares.require()= loads a file and returns itsmodule.exports.
// prices.js (CommonJS)
const TAX_RATE = 0.18;
function addTax(price) {
return price + price * TAX_RATE;
}
module.exports = { addTax };
// main.js (CommonJS)
const { addTax } = require("./prices.js");
console.log(addTax(1000)); // 1180
require() exists only in Node.js:
require() does not exist outside Node.js
const { addTax } = require("./prices.js");
console.log(addTax(1000));
CommonJS vs ES modules
ES modules = import/export, part of the ECMAScript standard.
| ES modules | CommonJS | |
|---|---|---|
| Share a value | export | module.exports = … |
| Load a module | import … from "./file.js" | require("./file.js") |
| Works in browsers | yes | no, not without a build tool |
| Works in Node.js | yes, in .mjs files or with "type": "module" in package.json | yes, the default for .js files, and always in .cjs files |
In Node.js, package.json decides: with "type": "module", every .js file is an ES module.
{
"name": "shop",
"type": "module"
}
Use ES modules for new code; learn to read CommonJS.
Easy way to remember: export = put it on the shelf; import = take it off the shelf. Unshelved things stay in the back room.
TL;DR
- A module's names are private;
exportshares,importreceives. - Named exports use
{ }and exact names; one default export per file, any name. asrenames;import * as nscollects everything.- Browsers need
type="module",./paths and.jsextensions, served over http. import()loads later and returns a promise;requireis CommonJS (Node.js).
Try this
In Load a coupon module only when a coupon is entered, swap the first two checkouts. The loading line now appears first, because the coupon checkout is the first to need the module.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
<script src="main.js"> with imports | Every script is a module | Add type="module" | Cannot use import statement outside a module |
import { x } from "./prices" | The browser adds .js | Write the extension | A 404 |
from "prices.js" | It means this folder | Start with ./ | Failed to resolve module specifier |
import { formatPrice } for a default export | Braces always work | No braces for defaults | does not provide an export named |
Opening index.html from disk | Modules work on file:// | Serve it over http | Modules are blocked |
require() in the browser | It is built in everywhere | Use import | require is not defined |
Quick reference
| Syntax | Meaning |
|---|---|
export const TAX_RATE = 0.18; | a named export, written on the declaration |
export { addToCart, cartCount }; | a list of named exports, usually at the bottom of the file |
export default function formatPrice() {} | the module's one default export |
import { addTax } from "./prices.js"; | import a named export, using its exact name |
import formatPrice from "./formatPrice.js"; | import the default export, under any name |
import showPrice, { CURRENCY } from "./format.js"; | the default and a named export in one line |
import { addTax as addGst } from "./prices.js"; | import under a new name |
export { calculateTotal as total }; | export under a new name |
import * as prices from "./prices.js"; | every export, as properties of one object |
<script type="module" src="main.js"> | load a file as a module in the browser |
await import("./coupons.js") | load a module on demand; returns a promise |
const { addTax } = require("./prices.js"); | CommonJS import, in Node.js |
module.exports = { addTax }; | CommonJS export, in Node.js |
Exercises
What to Remember
- One file, one job; share only what others need.
- Named exports by default; get the paths right.
- Load rarely used code with
import().
Next: Clean Coding. Strict mode, modern habits like const, let and ===, and clear names.