How to Use JavaScript Modules - Importing and Exporting
JavaScript modules provide a way to structure and organize your code into separate files that can be imported and used in other parts of your application. In this guide, we'll explore how to use JavaScript modules by importing and exporting code snippets.
Creating a Module
A module is a JavaScript file that contains code you want to reuse. To export items from a module, you can use the export
keyword. Here's an example:
math.js
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Importing a Module
To use the code from a module in another file, you can use the import
statement. Here's how to import the add
function from the math.js
module:
main.js
// main.js
import { add } from './math.js';
const result = add(5, 3);
console.log(result); // Outputs: 8
Importing with Aliases
You can use aliases to rename imported items for clarity:
// main.js
import { add as addition } from './math.js';
const result = addition(5, 3);
console.log(result); // Outputs: 8
Importing All Exports
If you want to import all exports from a module, you can use the *
wildcard:
// main.js
import * as mathFunctions from './math.js';
const sum = mathFunctions.add(5, 3);
const difference = mathFunctions.subtract(5, 3);
console.log(sum); // Outputs: 8
console.log(difference); // Outputs: 2
Default Exports
A module can also have a default export. A default export is the fallback value when you import from a module without specifying a name. Here's an example:
greet.js
// greet.js
export default function(name) {
return `Hello, ${name}!`;
}
main.js
// main.js
import greet from './greet.js';
const message = greet('Alice');
console.log(message); // Outputs: 'Hello, Alice!'
Conclusion
JavaScript modules make it easier to organize and reuse your code, allowing you to maintain clean and modular projects. By exporting and importing functions, classes, or variables, you can create a more maintainable and scalable codebase.
Experiment with JavaScript modules in your projects to take advantage of their code organization and reusability benefits.