import
and export
syntax allows developers to share functionality between different JavaScript files easily. This blog post will delve into the fundamental concepts, usage methods, common practices, and best practices of using import
and export
in JavaScript ES6 modules.In JavaScript, a module is simply a file. Each module has its own scope, which means that variables, functions, and classes defined in one module are not accessible in other modules by default. The export
keyword is used to make variables, functions, or classes available outside of the module, and the import
keyword is used to bring those exported items into another module.
Named exports allow you to export multiple values from a module. You can export variables, functions, or classes by specifying their names.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
A module can have one default export. The default export is useful when a module only has one main thing to export.
// greeting.js
const greeting = () => {
return 'Hello, World!';
};
export default greeting;
To import named exports, you need to specify the names of the exports inside curly braces.
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
When importing a default export, you don’t need to use curly braces. You can give the imported item any name you like.
// main.js
import greeting from './greeting.js';
console.log(greeting()); // Output: Hello, World!
You can combine named and default imports in a single import statement.
// main.js
import defaultExport, { add, subtract } from './math.js';
It’s a good practice to organize your modules based on their functionality. For example, you can have separate modules for handling data, UI components, and utility functions.
You can use aliases when importing named exports to avoid naming conflicts.
// main.js
import { add as addition, subtract as subtraction } from './math.js';
console.log(addition(5, 3)); // Output: 8
console.log(subtraction(5, 3)); // Output: 2
Each module should have a single responsibility. This makes the code easier to understand, test, and maintain.
If a module has multiple things to export, use named exports instead of default exports. This makes it clear what is being exported and imported.
JavaScript ES6 modules with the import
and export
syntax provide a powerful way to organize and share code. By understanding the fundamental concepts, different export and import syntaxes, and following common and best practices, you can write more modular, maintainable, and reusable JavaScript code.