ES Modules
ES Modules․ import և export modern in 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.
There are two main ways to export values in ES Modules: named export and default export.
// greet.js file
export function greet(name) {
return `Hello, ${name}!`;
}
export const message = 'Welcome to our website.';
// greet.js file
export default function greet(name) {
return `Hello, ${name}!`;
}
With default export, you can export one primary value from a file.
Importing is done according to the export style:
// main.js file
import { greet, message } from './greet.js';
console.log(greet('Ani')); // Hello, Ani!
console.log(message); // Welcome to our website.
// main.js file
import greet from './greet.js';
console.log(greet('Ani')); // Hello, Ani!
// 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.
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.
require()
and module.exports
.import
and export
.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.