In JavaScript, modules are self-contained units of code that can expose assets to other modules using export
and consume assets from other modules using import
. This mechanism is essential for building modular and reusable code in modern JavaScript applications.
Default Exports
- A module can have only one default export.
- To export a default asset, use the
default
keyword before the exported entity. - To import a default export, you can directly assign it to a variable without specifying the exported name:
// Exporting a default asset
export default function greet(name) {
console.log(`Hello, ${name}!`);
}
// Importing the default export
import greet from './myModule';
Named Exports
- A module can have multiple named exports.
- To export a named asset, use the
export
keyword before the exported entity and give it a name. - To import named exports, you must specify the names of the assets you want to import:
// Exporting named assets
export function greet(name) {
console.log(`Hello, ${name}!`);
}
export function farewell(name) {
console.log(`Goodbye, ${name}!`);
}
// Importing named exports
import { greet, farewell } from './myModule';
Combining Default and Named Exports
You can have both a default export and named exports in a single module:
export default function greet(name) {
console.log(`Hello, ${name}!`);
}
export function farewell(name) {
console.log(`Goodbye, ${name}!`);
}
To import both the default and named exports:
import greet, { farewell } from './myModule';
Key Points to Remember
-
export
is used to expose assets from a module. -
import
is used to consume assets from other modules. - A module can have only one default export.
- Named exports can be imported individually or collectively.
- The names used for imports are arbitrary and don't have to match the names used in the exported module.
Practical Example
Consider a React component:
import React from 'react';
export default function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
In this example, the Greeting
component is exported as the default export. It can be imported and used in other components:
import Greeting from './Greeting';
function MyComponent() {
return <Greeting name="Alice" />;
}
By understanding exports and imports, you can effectively organize and reuse code in your JavaScript projects.