Understanding Modules in VueJS: ES Modules vs. CommonJS
By stajic.de – Your tech insights hub
From module patterns and AMD loaders to today’s ESM and component-driven frameworks like Vue.js, the ecosystem has matured in amazing ways.
Vue.js is now one of the most popular JavaScript frameworks for building modern web applications.
Whether you’re working with single-file components, managing a store (like Vuex or Pinia),
or building a large-scale application, modules are at the core of organizing your codebase.
But when it comes to modules in Vue (and JavaScript in general), developers often come across
two common formats: ES Modules (ESM) and CommonJS (CJS).
Let’s break down their differences, benefits, and how they relate to Vue.js components.
🧩 What Are Modules in JavaScript?
Modules help developers separate code into smaller, manageable files. You can export functions, variables, or classes from one file and import them into another.
There are two primary types of modules:
- ES Modules (also called ESM)
- CommonJS (CJS)
1. ES Modules (ESM)
// myModule.js
export const greeting = 'Hello';
// main.js
import { greeting } from './myModule.js';
- Native to modern JavaScript (used in browsers and Node.js from v14+)
- Static imports (can be analyzed at compile time)
- Tree-shaking support: removes unused code during bundling
- Works seamlessly with Vue SFCs (.vue files) using tools like Vite or Webpack
Best for: Modern VueJS projects (especially with Vite or Vue CLI 5+)
2. CommonJS (CJS)
// myModule.js
const greeting = 'Hello';
module.exports = { greeting };
// main.js
const { greeting } = require('./myModule.js');
- Default module system in Node.js (before ESM support)
- Uses
require()
andmodule.exports
- Synchronous loading (not suitable for frontend/browsers directly)
- Often used in older Vue setups or when integrating with NodeJS services
Best for: Server-side Vue apps (like Nuxt with SSR), Node-based tooling, or older setups
🚀 Benefits of Using ES Modules in VueJS
Feature | ES Modules (import/export) | CommonJS (require) |
---|---|---|
Native to browser | ✅ | ❌ (needs bundler) |
Tree-shaking | ✅ | ❌ |
Async support | ✅ (top-level await) | ❌ |
Vue 3 compatibility | ✅ | ✅ (with extra setup) |
Readability | ✅ Modern syntax | 🟡 Verbose syntax |
📦 VueJS Components as Modules
Vue components themselves are modules!
// HelloWorld.vue
<template>
<div>Hello {{ name }}</div>
</template>
<script>
export default {
props: ['name']
}
</script>
// main.js
import HelloWorld from './components/HelloWorld.vue';
createApp(App).component('HelloWorld', HelloWorld).mount('#app');
✅ Summary
- Use ES Modules for frontend Vue projects. It’s modern, efficient, and aligns perfectly with Vue 3 and Vite.
- Use CommonJS when working with legacy systems or integrating with NodeJS backends.
- Always aim for modularity in VueJS by splitting logic, components, and utilities into reusable modules.