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:
javascriptimport { 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:
javascriptimport { 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:
javascriptimport { 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.