Welcome to our in-depth guide on ES6 Modules! By the end of this tutorial, you'll have a solid understanding of how to use these powerful features to structure your JavaScript projects more efficiently.
Let's start with the basics:
ES6 Modules are a modern way to write and manage JavaScript code. They allow you to break down a large project into smaller, more manageable pieces, making it easier to maintain and understand.
To import a module, use the import keyword followed by the module name.
// Import a module named 'myModule'
import { functionName } from 'myModule';In the above example, we're importing a function named functionName from the myModule file.
To make a function, class, or variable available to other modules, use the export keyword.
// myModule.js
export function functionName() {
// Your code here
}In the above example, we've created a module named myModule and exported a function named functionName.
If a module has only one default export, you can import it using the import keyword without curly braces.
// myModule.js
export default function functionName() {
// Your code here
}
// Import the default export
import functionName from 'myModule';You can also export multiple functions, classes, or variables from a single file using named exports.
// myModule.js
export function function1() {
// Your code here
}
export function function2() {
// Your code here
}To import named exports, use the curly braces syntax.
// Import named exports
import { function1, function2 } from 'myModule';Let's create a simple example of a calculator module that exports two functions: add and subtract.
calculator.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}index.js
import { add, subtract } from './calculator';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2Which keyword is used to import a module in ES6?
What does the `export` keyword do in ES6 Modules?
How do you import the default export from a module?
Happy learning! 🎉