Export vs Export Default in JavaScript
There are two ways to export code from modules saved in an external .js file when you want to reference it in your code:
export
Use export
when you want to export multiple named values from a module. You can export variables, functions, classes, or objects. When importing these named exports in another module, you need to use the same name within curly braces {}
. You can export multiple values by either using the export
keyword in front of each value or by using a single export statement with an object containing all the named export.
Example 1. “export”
// file: moduleA.js
export const value1 = 42;
export function func1() { /* ... */ }
export class Class1 { /* ... */ }
// file: main.js
import { value1, func1, Class1 } from './moduleA.js';
export default
export default
: Use export default
when you want to export a single value from a module, which will be the default export. This can be a variable, function, class, or object. When importing the default export in another module, you don't need to use curly braces, and you can assign any name you like to the imported value.
Example 2. “export default”
// file: moduleB.js
const value2 = 21;
export default…