乐闻世界logo
搜索文章和话题

How to export imported object in ES6?

1个答案

1

In ES6, JavaScript introduced the module system, enabling developers to share and reuse code using the export and import syntax. Here are the steps and examples for exporting and importing objects in ES6:

Export

Two primary export methods exist: Named Exports and Default Exports.

Named Exports

Named Exports allow you to export multiple values, each associated with a specific name. Here is an example:

javascript
// File: mathUtils.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;

Here, we export two functions: add and subtract.

Default Exports

Default Exports allow you to export a single value as the default for the module. Here is an example:

javascript
// File: StringUtils.js const greet = (name) => `Hello, ${name}!`; export default greet;

Here, we export the function greet as the default export.

Import

Corresponding to exports, imports are categorized into importing named exports and importing default exports.

Importing Named Exports

You can import one or more named exports as follows:

javascript
// File: app.js import { add, subtract } from './mathUtils.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(5, 3)); // Output: 2

You can also alias imported members using the as keyword:

javascript
import { add as addNumbers } from './mathUtils.js'; console.log(addNumbers(5, 3)); // Output: 8

Importing Default Exports

You can import a default export as follows:

javascript
// File: app.js import greet from './StringUtils.js'; console.log(greet('Alice')); // Output: "Hello, Alice!"

Mixed Imports

When a module contains both named exports and default exports, you can import them together as follows:

javascript
// File: utils.js export const multiply = (a, b) => a * b; export default (a, b) => a / b; // Import file import divide, { multiply } from './utils.js'; console.log(multiply(4, 3)); // Output: 12 console.log(divide(4, 2)); // Output: 2

These are the fundamental export and import methods in ES6. Depending on your specific requirements, you can choose the approach that best suits your project.

2024年6月29日 12:07 回复

你的答案