Explain ES6 modules (import/export). Compare with CommonJS and discuss module bundling.

3 minintermediatejavascriptes6modulesimportexport

Quick Answer

ES6 modules provide a standardized way to organize and share code between files.

Detailed Answer

Explain ES6 modules (import/export). Compare with CommonJS and discuss module bundling.

ES6 modules provide a standardized way to organize and share code between files.

Export Syntax:

// Named exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class Calculator { multiply(a, b) { return a * b; } }

// Default export
export default function subtract(a, b) { return a - b; }

// Mixed exports
export const VERSION = '1.0.0';
export default class MathUtils { static divide(a, b) { return a / b; } }

Import Syntax:

// Named imports
import { PI, add, Calculator } from './math.js';

// Default import
import subtract from './math.js';

// Mixed imports
import MathUtils, { VERSION } from './math.js';

// Namespace import
import * as math from './math.js';

// Dynamic import
const { add, subtract } = await import('./math.js');

CommonJS vs ES6 Modules:

// CommonJS
const fs = require('fs');
module.exports = { readFile: fs.readFile };

// ES6 Modules
import fs from 'fs';
export { readFile: fs.readFile };

Module Bundling:

// Code splitting
const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));

// Tree shaking (only used exports are bundled)
import { debounce } from 'lodash-es'; // Only debounce is bundled
import _ from 'lodash'; // Entire library bundled