ES Modules: import and export in Modern JavaScript
ES Modules (ESM) is JavaScript's standard module system, officially introduced in ECMAScript 2015 (ES6). It allows organizing code in a cleaner and more efficient way, both in browsers and server environments (like Node.js).
ES Modules work asynchronously and use the import and export keywords for module importing and exporting.
How to Export in ES Modules
There are two main ways to export values in ES Modules: named export and default export.
Named Export
// greet.js file
export function greet(name) {
return `Hello, ${name}!`;
}
export const message = 'Welcome to our website.';
Default Export
// greet.js file
export default function greet(name) {
return `Hello, ${name}!`;
}
With default export, you can export one primary value from a file.
How to Import in ES Modules
Importing is done according to the export style:
Named Imports
// main.js file
import { greet, message } from './greet.js';
console.log(greet('Ani')); // Hello, Ani!
console.log(message); // Welcome to our website.
Default Import
// main.js file
import greet from './greet.js';
console.log(greet('Ani')); // Hello, Ani!
Combining Named and Default Import
// In greet.js file
export default function greet(name) {
return `Hello, ${name}!`;
}
export const message = 'Welcome to our website.';
// In main.js file
import greet, { message } from './greet.js';
console.log(greet('Ani')); // Hello, Ani!
console.log(message); // Welcome to our website.
Features of ES Modules
- Asynchronous Import - The browser can load modules asynchronously, enabling faster loading.
- Strict Syntax - Modules always operate in strict mode.
- Browser Support - Modern browsers (Chrome, Firefox, Safari, etc.) directly support ES Modules without special bundlers.
- Static Analysis - import/export statements can be analyzed at compile time, enabling optimization techniques like tree-shaking.
How to Use in Browsers
To use ES Modules directly in browsers, you need to specify type="module" in the <script> tag:
<script type="module" src="main.js"></script>
The browser recognizes this as a module file and loads it accordingly.
CommonJS vs ES Modules Comparison
- CommonJS - Synchronous and designed for server-side environments.
- ES Modules - Asynchronous and designed for both browsers and servers.
- CommonJS uses
require()andmodule.exports. - ES Modules use
importandexport.
Conclusion
ES Modules has become JavaScript's standard today, enabling clean, fast, and efficient code. In the next article, we'll discuss how CommonJS and ES Modules coexist in Node.js and what challenges you might face when using them.