Web · Languages

Organise JavaScript with ES modules

As a script grows, keeping everything in one file makes responsibilities and dependencies harder to follow. ES modules let you split code without introducing a framework.

Practical guideLanguages

Split code by responsibility

Create one module for each coherent role rather than one tiny file per function.

  • Separate interface logic, data handling and utilities.
  • Name files according to their actual purpose.
  • Avoid modules depending on the entire application when they only need a small part.

Control imports and exports

Expose only what other modules need and keep implementation details private to the file.

  • Prefer named exports for reusable functions.
  • Avoid circular dependencies between modules.
  • Centralise shared constants only when it improves clarity.

Load modules cleanly

In the browser, use type="module" and keep file paths explicit.

  • Use <script type="module"> for the entry point.
  • Retest relative paths after moving files.
  • Limit side effects that run automatically when a module is imported.

Practical checklist

  • A clear JavaScript entry point.
  • Modules grouped by responsibility.
  • Explicit imports and exports.
  • No unnecessary circular dependency.
  • The site still works after a direct page reload.