Default exports and named imports
Explain the difference between default and named exports, showing how to properly import a default exported function.
// utils.js
export default function greet(name) {
return `Hello, ${name}!`;
}
export const utilsVersion = '1.0.0';
In the file 'utils.js', we have a default export 'greet', which is a function that takes a name and returns a greeting message. Additionally, we have a named export 'utilsVersion' that simply exports a version string.
// main.js
import greet, { utilsVersion } from './utils.js';
console.log(greet('Alice')); // Outputs: Hello, Alice!
console.log(`Utils version: ${utilsVersion}`); // Outputs: Utils version: 1.0.0
In the file 'main.js', we import the default exported function 'greet' from 'utils.js' without using curly braces. We also import a named export 'utilsVersion' by using curly braces. We then use these imports in our code to display the greeting message and the utils version.