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
// Exporting a default asset export default function greet(name) { console.log(`Hello, ${name}!`); } // Importing the default export import greet from './myModule';
Named Exports
// 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
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.
The above is the detailed content of Understanding Exports and Imports in JavaScript. For more information, please follow other related articles on the PHP Chinese website!