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 }) { returnHello, {name}!
; }
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; }
By understanding exports and imports, you can effectively organize and reuse code in your JavaScript projects.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3