How to use modules in JavaScript
JavaScript modules provide a way to organize code into separate files with explicit imports and exports, enabling better code structure and reusability.
As the creator of CoreUI, a widely used open-source UI library, I’ve architected modular JavaScript systems across countless projects and component libraries.
From my 25 years of experience in web development, the most modern and effective approach is to use ES6 module syntax with import and export statements.
This pattern provides clean dependency management and tree-shaking capabilities for optimized bundles.
Use export to expose functions, objects, or values from modules and import to use them in other files.
// math.js - Named exports
export function add(a, b) {
return a + b
}
export const PI = 3.14159
export class Calculator {
multiply(a, b) {
return a * b
}
}
// utils.js - Default export
export default function formatCurrency(amount) {
return `$${amount.toFixed(2)}`
}
// app.js - Importing modules
import formatCurrency from './utils.js'
import { add, PI, Calculator } from './math.js'
// Using imported functionality
console.log(add(5, 3)) // 8
console.log(PI) // 3.14159
console.log(formatCurrency(19.99)) // $19.99
const calc = new Calculator()
console.log(calc.multiply(4, 5)) // 20
Named exports allow multiple exports from a single module using the export keyword before declarations or in export lists. Default exports provide a single main export per module using export default. Import statements bring functionality from other modules - use curly braces for named imports and direct imports for default exports. Modern bundlers like Webpack and Rollup support tree-shaking to remove unused exports from final bundles.
This is the same modular architecture we use in CoreUI to organize components and utilities for maximum reusability and maintainability.
For Node.js environments, ensure your package.json includes "type": "module" or use .mjs file extensions to enable ES6 module syntax.



