JavaScript Modular Code
In the early days of JavaScript, scripts were just long files attached to HTML pages. As applications grew into complex SPAs (Single Page Applications), this became unmaintainable. Enter ES6 Modules.
Why Modularize?
Modules allow you to break your code into manageable, independent files. This provides encapsulation (variables in a module don't leak into the global window object by default), reusability, and dependency management.
Named vs Default Exports
There are two ways to export data from a module:
- Named Exports: Use
export const a = 1;. You can have many named exports per file. When importing, you must use curly braces:import { a } from './file.js'; - Default Exports: Use
export default Component;. You can only have ONE default export per file. You import it without braces and can name it anything:import MyComp from './file.js';
The HTML Connection
To use ES6 modules natively in the browser, you must include the script tag with thetype="module" attribute. This tells the browser to parse the file differently, enabling features like strict mode by default and deferring execution.
View CommonJS vs ES6 Notes+
Node.js historically used CommonJS modules (require() and module.exports). ES6 modules (import/export) are the modern standard for both browser and server. When working in modern frontend frameworks (React, Next.js, Vue), you will almost exclusively use ES6 module syntax.
