ES modules provide a standard way to organize and share JavaScript code. Here's how to use them effectively.
Basic Export and Import
Default Exports
Import Variations
Export Variations
Dynamic Imports
Module Patterns
Circular Dependencies
Module Scope
Node.js Specifics
Browser Usage
Module Design
Tree Shaking
Testing with Modules
Best Practices
Export Design:
✓ One module = one responsibility
✓ Named exports for utilities
✓ Default export for main item
✓ Use barrel files for public API
Import Organization:
✓ External packages first
✓ Internal absolute paths
✓ Relative paths last
✓ Group by type
File Structure:
✓ index.js for public API
✓ Consistent naming
✓ Colocate related code
✓ Avoid deep nesting
Avoid:
✗ Circular dependencies
✗ Wildcard re-exports (*)
✗ Importing from deep paths
✗ Side effects in modules
Conclusion
ES modules are the standard for JavaScript code organization. Use named exports for utilities and default exports for main functionality. Leverage dynamic imports for code splitting, barrel files for clean public APIs, and import maps for browser deployment. Keep modules focused, avoid circular dependencies, and design for tree shaking to create maintainable, efficient code.