30 Mins upper-intermediate
19. ES6 Modules
Architecture
Modules
You cannot build a production application in a single 10,000-line app.js file. ES6 Modules allow you to split your code into multiple files, explicitly declaring what is shared and what remains private.
๐ค Exporting Data
In your utility files, you must export the functions or variables you want other files to see.
// Inside mathUtils.js
// Named Exports (You can have multiple)
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// Default Export (Only one per file)
const calculatorName = "SuperCalc";
export default calculatorName;
๐ฅ Importing Data
In your main file, you import those specific pieces of logic.
// Inside app.js
// Import Named Exports (Must use exact names inside curly braces)
import { add, subtract } from './mathUtils.js';
// Import Default Export (Can name it anything you want)
import calcName from './mathUtils.js';
console.log(calcName); // SuperCalc
console.log(add(10, 5)); // 15
HTML Note: To use ES6 modules in the browser, your script tag must include the type attribute:
<script type="module" src="app.js"></script>.Knowledge Check
Ready to test your understanding of 19. ES6 Modules?