JavaScript + Node.js track

Lesson 23 · Part 6: Browser APIs

ES Modules

`import`/`export` and `<script type="module">`

Part 6: Browser APIs2 min readFree lesson

Level: Advanced | Player: 22_Storage

Learning Objectives

  • You can use import/export from ES Modules.
  • Distinguish between named export and default export.
  • Load the module in the browser with <script type="module">.
  • Modules are bundled and provided through re-export.

1. Why modules?

Putting all your code in one file leads to conflicts and difficult maintenance. Modules isolate scope by file and expose only what is needed.

2. export — named / default

// math.mjs
export const PI = 3.14159;
export function add(a, b) { return a + b; }

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

As the name suggests, named exports can only have one default per module.

3. import

import multiply, { PI, add } from './math.mjs';
import * as math from './math.mjs';
import { add as plus } from './math.mjs';

Default is written without curly braces, and named is written within curly braces.

4. Use in browser

<script type="module" src="./02_import.mjs"></script>

type="module" must be present for the import statement to work. The module is automatically set to defer and is in strict mode.

5. re-export

When providing multiple modules bundled in one entry point.

// index.mjs
export { add, PI } from './math.mjs';
export { format } from './format.mjs';

Core example

file Contents covered
01_export.mjs named & default export
02_import.mjs 01 import
03_named_default.mjs Blending the Two Ways
04_reexport.mjs re-export pattern
index.html <script type="module">

index.html needs to be opened as a local server (file:// is a CORS issue).

⚠️ Common Mistakes

  1. type="module" is omitted, so import is a SyntaxError.
  2. Import default with braces { }.
  3. ./ is missing in the relative path → mistaken for a bare module.
  4. Extension .mjs/.js missing (browser needs to specify).
  5. Open directly with file:// — using local server.

❓ Frequently Asked Questions (FAQ)

Q1. Difference between .js and .mjs? A. In Node, .mjs follows ESM and .js follows type in package.json. In the browser, just look at type="module" and both are OK. Q2. Can I mix it with CommonJS? A. It is possible to a limited extent in Node. This is covered in Part 24. Q3. Is there also dynamic import? A. Runtime load is possible with await import('./x.mjs').

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_export.mjsJavaScript
/**
 *Examples of named export and default export
 */
export const PI = 3.14159;

/**
 *sum of two numbers
 */
export function add(a, b) {
  return a + b;
}

/**
 *Product of two numbers (default)
 */
export default function multiply(a, b) {
  return a * b;
}
src/02_import.mjsJavaScript
/**
 *Import and use from 01_export.mjs
 */
import multiply, { PI, add } from './01_export.mjs';

console.log('PI:', PI);
console.log('1+2 =', add(1, 2));
console.log('3*4 =', multiply(3, 4));
src/03_named_default.mjsJavaScript
/**
 *Import named and default together / use alias
 */
import multiply, { add as plus, PI } from './01_export.mjs';
import * as math from './01_export.mjs';

console.log(plus(10, 20));
console.log(multiply(2, PI));
console.log('Use namespace:', math.add(5, 7));
src/04_reexport.mjsJavaScript
/**
 *re-export — bundle other modules and re-export them
 *Externally, you only need to import this one file.
 */
export { add, PI } from './01_export.mjs';
export { default as multiply } from './01_export.mjs';
src/index.htmlHTML
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
<title>ESM Demo</title>
  </head>
  <body>
<h1>ESM Demo</h1>
<p>Check the console.</p>
    <script type="module" src="./02_import.mjs"></script>
  </body>
</html>

Assignment

Assignment 1

Create the two functions utils.mjs, formatPrice(n) (e.g. 1000 → "1,000 won"), and discount(price, percent) as named exports, import them from main.mjs, and print them on the HTML page.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01_main.mjsJavaScript
/**
 *Display on screen using utils module
 */
import { formatPrice, discount } from './homework_01_utils.mjs';

const price = 25000;
const sale = discount(price, 20);

const out = document.getElementById('out');
out.innerHTML = `
<p>Regular price: ${formatPrice(price)}</p>
<p>Discount price (20%): ${formatPrice(sale)}</p>
`;
homework_01_utils.mjsJavaScript
/**
 *Format the price in thousands with a comma and 'won'
 */
export function formatPrice(n) {
  return `${n.toLocaleString('ko-KR')} won`;
}

/**
 *Discount price calculation
 */
export function discount(price, percent) {
  return Math.floor(price * (1 - percent / 100));
}
homework_01.htmlHTML
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
<title>Utility module demo</title>
  </head>
  <body>
<h1>Calculate price</h1>
    <div id="out"></div>
    <script type="module" src="./homework_01_main.mjs"></script>
  </body>
</html>

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now