CommonJS vs ESM: diferencias y errores al mezclar módulos

Descubre las diferencias entre CommonJS y ESM, por qué mezclarlos causa errores de build y cómo migrar a ESM con tree-shaking. Optimiza tu código.

29 jun 2026 • 3 min read • Q2BSTUDIO Team

Problemas al combinar CommonJS y ESM en Node.js

En el ecosistema de desarrollo con Node.js, la coexistencia de dos sistemas de módulos, CommonJS (basado en require y module.exports) y ES Modules (basado en import y export), representa uno de los desafíos técnicos más frecuentes al construir aplicaciones modernas. Cada sistema tiene una filosofía distinta: CommonJS carga los módulos de forma síncrona en tiempo de ejecución, mientras que ESM realiza una resolución estática durante el parseo, antes de ejecutar el código. Esta diferencia fundamental afecta directamente a optimizaciones como el tree-shaking, que solo es efectivo con ESM al poder determinar con exactitud qué símbolos se utilizan. En Q2BSTUDIO, como empresa especializada en desarrollo de aplicaciones a medida, hemos visto numerosos proyectos que sufren errores de compilación y runtime por mezclar ambos sistemas sin la configuración adecuada.

Uno de los escenarios más comunes es el error 'Cannot use import statement outside a module', que ocurre cuando se emplea sintaxis ESM en un archivo que el intérprete trata como CommonJS. La causa suele estar en el campo 'type' del package.json o en la extensión del archivo (.mjs vs .cjs). Para evitarlo, es fundamental mantener la coherencia: si se opta por ESM, establecer 'type': 'module' en el package.json y usar extensiones .mjs para archivos excepcionales. Del mismo modo, al intentar importar un paquete CommonJS desde un módulo ESM, es frecuente encontrarse con el error 'named export not found', ya que CommonJS no exporta nombres de forma estática. La solución idiomática es usar la importación por defecto y luego desestructurar. Estos conocimientos son clave en el desarrollo de software a medida, donde la integración de librerías de terceros es constante.

La optimización del tamaño del bundle mediante tree-shaking es especialmente relevante en aplicaciones que requieren alto rendimiento, como aquellas que incorporan inteligencia artificial y agentes IA. En Q2BSTUDIO aplicamos técnicas avanzadas de bundling utilizando ESM para reducir al mínimo el código no utilizado, lo que se traduce en cargas más rápidas y menor consumo de recursos. Además, cuando desplegamos en servicios cloud AWS y Azure, esta eficiencia impacta directamente en los costos operativos. Por otro lado, la gestión de dependencias circulares (circular dependencies) difiere entre CommonJS, que puede devolver valores parciales, y ESM, que usa live bindings resultando más predecible. Identificar y rediseñar estos ciclos es parte de las buenas prácticas que implementamos en nuestros proyectos de ciberseguridad y servicios inteligencia de negocio.

Para proyectos nuevos, la recomendación es adoptar ESM de forma consistente desde el inicio, ya que es el estándar del lenguaje y permite aprovechar todas las ventajas del análisis estático. Al migrar una base de código existente, es aconsejable hacerlo por capas, reemplazando gradualmente require por import, ajustando la configuración de Node y probando cada paso. En Q2BSTUDIO ofrecemos servicios de consultoría para migrar aplicaciones legacy a arquitecturas modulares modernas, y también desarrollamos soluciones de inteligencia de negocio con herramientas como Power BI, así como plataformas de ia para empresas y agentes IA que se benefician de una base de código limpia y optimizada. Si tu proyecto enfrenta errores de módulos o deseas mejorar la eficiencia del build, nuestro equipo está preparado para ayudarte a implementar la mejor estrategia.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat