Modules: import & export
Split your code across files and share functions between them — how every real project is organised.
What you will learn
- Export values from a file
- Import them into another
- Understand why modules matter
Share code between files
Real apps split code into many files (modules). You export from one file and import into another.
Picture two files. The first one, math.js, exports the things it wants to share with other files.
// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14159;The word export in front of add and PI marks them as "available to other files". Anything without export stays private to math.js.
The second file, app.js, imports those shared things and uses them.
// app.js
import { add, PI } from './math.js';
console.log(add(2, 3)); // 5
console.log(PI);import { add, PI } from './math.js' pulls those two names in by matching their names exactly. After that line, add and PI work here as if they were written in this file — so add(2, 3) returns 5.
Note: Output (in the console): 5 3.14159
- In
math.js, putexportin front of each value you want to share. - In
app.js,import { ... } from './math.js'to bring those names in. - Use the imported names normally — they behave just like local code.
Note: To use modules in the browser, add type="module" to your script tag: <script type="module" src="app.js"></script>. React and Node use this import/export system everywhere.
Tip: There is also a default export (export default) for a file’s main thing, imported without braces. You will see both styles constantly in React projects.
Q. Which keyword brings a function from another file into this one?
✍️ Practice
- Create a
utils.jsthat exports two functions and import them into another file. - Try a
default exportand import it without braces.
🏠 Homework
- Split a small program into two files using import/export.