How change require to import with key in ES6?

1个答案

1
最佳答案

In ES6, you can import specific values or functions using the import statement. This approach is known as named imports. Named imports allow you to select only the required parts from a module, rather than the entire module. This helps keep the code lean by importing only what is needed.

The basic syntax for named imports is as follows:

javascript
import { identifier } from 'modulePath';

Here, 'identifier' should be the name defined when exporting the module.

For example, consider a file named mathFunctions.js that defines multiple functions, as follows:

javascript
// mathFunctions.js export function add(x, y) { return x + y; } export function subtract(x, y) { return x - y; }

If you only want to import the add function, you can import it as follows:

javascript
import { add } from './mathFunctions.js'; console.log(add(2, 3)); // Output: 5

If you need to import multiple specific values, you can separate them with commas:

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

This import method improves code readability and maintainability, while also making the import process more explicit and straightforward.

2024年7月28日 12:13 回复

你的答案