Performance: ES Modules import and export
This concept affects the initial load time and parsing speed of JavaScript modules in the browser or Node.js environment.
Jump into concepts and practice - no test required
import { calculate } from './utils.js'; const result = calculate();
import * as utils from './utils.js'; const result = utils.calculate();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Import entire module with * | N/A | N/A | Increases script parsing time | [X] Bad |
| Import specific exports statically | N/A | N/A | Smaller script size, faster parsing | [OK] Good |
| Dynamic import for rarely used code | N/A | N/A | Defers loading, improves initial paint | [OK] Good |
| Static import of large unused modules | N/A | N/A | Blocks initial load, increases LCP | [X] Bad |
export and import in Node.js ES Modules?exportexport keyword allows parts of a file (like functions or variables) to be shared with other files.importimport keyword is used to bring those shared parts into another file to use them.greet in an ES Module file?export function functionName() {} to export a function.node main.js?// utils.js
export const value = 5;
export function double(x) { return x * 2; }// main.js
import { value, double } from './utils.js';
console.log(double(value));utils.js exports a constant value = 5 and a function double that multiplies input by 2.main.jsvalue and double, then calls double(value) which is double(5), returning 10.// math.js
export function add(a, b) { return a + b; }
// app.js
import { add } from './math';
console.log(add(2, 3));import { add } from './math'; but misses the .js extension required in Node.js ES Modules.add is correctly exported with export function add(), so no error there.// data.js
const secret = 'hidden';
export const visible = 'shown';
export default function getSecret() { return secret; }// index.js
import getSecret, { visible } from './data.js';
console.log(visible);
console.log(getSecret());node index.js?getSecret is the default export function returning secret. visible is a named export with value 'shown'.import getSecret, { visible } correctly imports default and named exports. Logging visible prints 'shown'. Calling getSecret() returns 'hidden'.