Curriculum Series

How do you import and export modules?

How do you import and export modules?

How do you import and export modules?

JavaScript

The short answer

Use export to share code from a file and import to use it in another. Named exports use curly braces on import, default exports do not. You can also use export default for the main thing a file provides, and dynamic import() for loading modules on demand.

Named exports and imports

JAVASCRIPT
1// math.js — named exports
2export function add(a, b) {
3 return a + b;
4}
5export function subtract(a, b) {
6 return a - b;
7}
8export const PI = 3.14159;
9
10// app.js — named imports (must match export names)
11import { add, subtract, PI } from './math.js';

You can rename on import:

JAVASCRIPT
1import { add as sum } from './math.js';
2sum(1, 2); // 3

Default exports and imports

JAVASCRIPT
1// Button.js — default export (one per file)
2export default function Button({ children }) {
3 return <button>{children}</button>;
4}
5
6// App.js — default import (any name works)
7import Button from './Button.js';
8import MyButton from './Button.js'; // also works

Combining both

JAVASCRIPT
1// api.js
2export default function fetchData() {
3 /* ... */
4}
5export function formatResponse(data) {
6 /* ... */
7}
8
9// app.js
10import fetchData, { formatResponse } from './api.js';

Re-exporting

Useful for creating barrel files (index.js that re-exports from multiple files):

JAVASCRIPT
1// components/index.js
2export { default as Button } from './Button.js';
3export { default as Input } from './Input.js';
4export { default as Modal } from './Modal.js';
5
6// Now import from one place
7import { Button, Input, Modal } from './components';

Dynamic imports

Load modules on demand:

JAVASCRIPT
1const module = await import('./heavy-library.js');
2module.doSomething();

Interview Tip

Show named vs default exports with a quick example each. Mention re-exporting for barrel files and dynamic imports for code splitting. This is a syntax question — keep examples short.

Why interviewers ask this

This tests fundamental module syntax knowledge. Interviewers want to confirm you know named vs default exports, how to combine them, and how to organize imports across files.

Finished reading?

Mark this topic as solved to track your progress.