# Import and Export

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Modules and Clean Coding
Source: https://www.devtutorials.ai/learn/javascript/modules-and-clean-code/import-and-export

> 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.

- `export` shares a value from a file.
- `import` brings 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.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="Two file boxes. prices.js has a private TAX_RATE and an exported formatPrice. An arrow carries formatPrice into main.js; TAX_RATE stays behind." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="30" y="30" width="200" height="110" rx="10" fill="#eff6ff" stroke="#2563eb" />
    <text x="130" y="52" textAnchor="middle" fontSize="13" fill="#1e40af">prices.js</text>
    <text x="50" y="82" fontSize="11" fontFamily="monospace" fill="#64748b">const TAX_RATE (private)</text>
    <text x="50" y="112" fontSize="11" fontFamily="monospace" fill="#1e40af">export formatPrice</text>
    <rect x="330" y="30" width="200" height="110" rx="10" fill="#f0fdf4" stroke="#16a34a" />
    <text x="430" y="52" textAnchor="middle" fontSize="13" fill="#166534">main.js</text>
    <text x="345" y="112" fontSize="11" fontFamily="monospace" fill="#166534">import &#123; formatPrice &#125;</text>
    <rect y="98" width="96" height="22" rx="4" fill="#fde68a" stroke="#ca8a04"><animate attributeName="x" values="150;340;340" keyTimes="0;0.5;1" dur="3s" repeatCount="indefinite" /></rect>
    <text y="113" fontSize="10" fontFamily="monospace" fill="#854d0e">formatPrice<animate attributeName="x" values="158;348;348" keyTimes="0;0.5;1" dur="3s" repeatCount="indefinite" /></text>
  </svg>
  <figcaption>Only exported names travel between files.</figcaption>
</figure>

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

1. What modules are, and module scope versus global scope.
2. Named exports, default exports and export lists.
3. Named, default, renamed (`as`) and namespace (`* as`) imports.
4. `type="module"`, path rules and common module errors.
5. 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`.

```js runnable browser-only title="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:

```text
addTax(1000): 1180
TAX_RATE from outside: undefined
```

### Why modules are needed

1. **Name clashes:** a name belongs only to its own file.
2. **Hidden needs:** `import` lines say exactly what a file depends on.
3. **Large files:** split a program into small files, each with one job.

```text
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:

```js runnable title="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:

```js runnable browser-only title="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:

```text
Exported label: IN prices in INR
Is region global?   false
Is currency global? false
```

```js
// 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.

```js
// 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.

```js
// 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.

```js
// 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.

```js
// main.js
import { addTax, formatPrice } from "./prices.js";

console.log(formatPrice(addTax(1000)));   // "₹1180.00"
```

```js runnable browser-only title="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:

```text
Total: ₹1180.00
```

A name that does not exist stops the module from loading, with a clear message:

```js runnable browser-only title="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:

```text
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"`.

```js
// main.js
import formatPrice from "./formatPrice.js";
import showPrice from "./formatPrice.js";   // also works: same function, different name
```

```js runnable browser-only title="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:

```text
₹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.

```js
// Renaming on the way in
import { addTax as addGst } from "./prices.js";

// Renaming on the way out
function calculateTotal(items) { /* ... */ }
export { calculateTotal as total };
```

```js runnable browser-only title="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:

```text
ORDER SUMMARY: ₹250.00
```

### Import everything (`import * as`)

Collects every export into one **namespace object**. A default export appears as `.default`.

```js
import * as prices from "./prices.js";

prices.addTax(1000);
prices.formatPrice(1180);
```

```js runnable browser-only title="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:

```text
Properties: [
  "TAX_RATE",
  "addTax",
  "default"
]
addTax(500): 590
default: prices module
```

All import styles in one project box:

```js runnable title="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.

```html
<!-- 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:

1. Start relative paths with `./` (this folder) or `../` (one folder up).
2. Write the extension: `./prices.js`, not `./prices`.

```js
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.

```js runnable browser-only title="A bare specifier cannot be resolved in the browser"
try {
  await import("lodash");
} catch (error) {
  console.log("Failed with a", error.name);
}
```

Expected output:

```text
Failed with a TypeError
```

### Common module errors and fixes

`import` in a file that is not a module:

```js runnable expect-error title="An import statement outside a module"
import { addTax } from "./prices.js";
console.log(addTax(1000));
```

`export` gives a different message for the same cause:

```js runnable expect-error title="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.

```js
// Load the chart code only when the button is pressed
chartButton.addEventListener("click", async () => {
  const { drawChart } = await import("./chart.js");
  drawChart(salesData);
});
```

```js runnable browser-only title="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:

```text
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`.

```js runnable browser-only title="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:

```text
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 its `module.exports`.

```js
// prices.js (CommonJS)
const TAX_RATE = 0.18;

function addTax(price) {
  return price + price * TAX_RATE;
}

module.exports = { addTax };
```

```js
// main.js (CommonJS)
const { addTax } = require("./prices.js");

console.log(addTax(1000));   // 1180
```

`require()` exists only in Node.js:

```js runnable expect-error title="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.

```json
{
  "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; `export` shares, `import` receives.
- Named exports use `{ }` and exact names; one default export per file, any name.
- `as` renames; `import * as ns` collects everything.
- Browsers need `type="module"`, `./` paths and `.js` extensions, served over http.
- `import()` loads later and returns a promise; `require` is 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

<div className="tscroll">

| 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 |

</div>

## 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.
