Import and Export in depth
Import and Export in depth: Named, Default, Dynamic Import
JavaScript's module system has made code organization much more convenient. The import
and export
statements allow transferring functions, objects, or entire modules between files. Let's examine in detail what options are available.
Named Export means we export specific variables or functions by name. When importing, we must use those exact names.
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
Important: Names must match exactly. You can use the as
keyword to rename imports.
// Rename imports
import { add as addition } from './math.js';
console.log(addition(5, 3)); // 8
Default Export means a file exports one primary value. When importing, you can use any name you want.
// logger.js
export default function log(message) {
console.log('Log: ' + message);
}
// app.js
import log from './logger.js';
log('Hello world'); // Log: Hello world
Important: When importing default exports, the name can be freely chosen since it's the main export of the file.
A file can have both default and named exports.
// user.js
export default function createUser(name) {
return { name };
}
export const admin = { name: 'Admin' };
// app.js
import createUser, { admin } from './user.js';
console.log(createUser('Anna')); // { name: 'Anna' }
console.log(admin); // { name: 'Admin' }
Dynamic Import means we can import modules only when they're actually needed. This helps reduce initial load and improves performance.
// dynamic.js
export function dynamicHello() {
console.log('Hello from dynamic world!');
}
// app.js
async function loadDynamic() {
const module = await import('./dynamic.js');
module.dynamicHello();
}
loadDynamic();
Important: Dynamic import returns a Promise and is typically used with async/await.
JavaScript's import
and export
mechanisms provide powerful tools for organizing and optimizing code. When you understand the differences between named, default, and dynamic imports, you'll be able to write cleaner, more optimized, and more professional code.