Modules organize code into reusable pieces. Here's how they work in JavaScript.
ES Modules (ESM)#
Loading code block...
Default Exports#
Loading code block...
Re-exporting#
Loading code block...
CommonJS (Node.js)#
Loading code block...
Dynamic Imports#
Loading code block...
Import Meta#
Loading code block...
Module Patterns#
Loading code block...
Circular Dependencies#
Loading code block...
Browser vs Node.js#
Loading code block...
Loading code block...
TypeScript Modules#
Loading code block...
Module Resolution#
Loading code block...
Tree Shaking#
Loading code block...
Best Practices#
Organization:
✓ One export per file for large exports
✓ Use barrel files (index.js) for folders
✓ Keep related code together
✓ Avoid deep nesting
Naming:
✓ Use descriptive file names
✓ Match export name to file name
✓ Use camelCase for functions
✓ Use PascalCase for classes/components
Imports:
✓ Group imports logically
✓ External packages first
✓ Then internal modules
✓ Use absolute imports for clarity
Avoid:
✗ Circular dependencies
✗ Side effects in modules
✗ Mixing ESM and CommonJS
✗ Default exports for utilities
Conclusion#
JavaScript modules enable clean code organization and reusability. Use ES modules for modern projects, understand CommonJS for Node.js compatibility, and leverage dynamic imports for code splitting. Keep modules focused, avoid circular dependencies, and structure imports for tree shaking.