Home Projects Portfolio Dashboard Export PDF Log in

Modernizing JavaScript: Moving to ES6 Modules

Legacy codebases often hold onto older patterns simply because they "just work." However, as projects grow, maintaining scattered function declarations and global scope pollution becomes a silent performance and debugging killer. In the "Plantilla" project, we recently completed a refactor to modernize the core JavaScript infrastructure by adopting ES6 modules.

Moving Beyond the Global Scope

In older JavaScript implementations, scripts were often loaded via simple tag order, relying on functions being attached to the global window object. This creates "spaghetti dependencies" where one file breaks if another isn't loaded in the precise, correct order.

By transitioning to ES6 modules (import/export), we turn our code into a dependency graph. This makes it explicit what each file needs to function.

Refactoring for Modularity

Before the change, we had patterns resembling classic script inclusion. After the transition, we focused on encapsulating logic. Instead of exposing everything to the global scope, we explicitly export only what is necessary.

// Before: Global function
function formatCurrency(value) { 
  return `$${value.toFixed(2)}`; 
}

// After: Exporting a module function
export const formatCurrency = (value) => {
  return `$${value.toFixed(2)}`;
};

This small change allows developers to import only the utilities they need (import { formatCurrency } from './utils.js'). It also enables tree-shaking—a process where modern bundlers remove unused code, resulting in smaller payloads for the end user.

The Benefits of Clean Boundaries

Adopting ES6 modules provides several immediate wins:

  1. Dependency Clarity: You can see exactly what a file requires at the top of the script.
  2. Strict Mode: ES6 modules run in strict mode by default, preventing accidental global variable creation.
  3. Testability: Isolated functions are much easier to unit test without mocking global states.

While the refactor required touching multiple files, the long-term payoff is a more resilient, predictable codebase that aligns with modern development standards.


Generated with Gitvlg.com

Modernizing JavaScript: Moving to ES6 Modules
JOSE ANTONIO HOLGADO BONET

JOSE ANTONIO HOLGADO BONET

Author

Share: