Module
Modules enable you to break your code into pieces, making it easier to maintain and scale applications. They are essential components of a programming language. In JavaScript, the situation was more complicated. Fortunately, it has now settled down to ES modules(ESM).
ES Modules
ESM is pretty stright forward:
myModule.js
export const pi = 3.14159
export function greet(name) {
console.log(`Hello, ${name}!`)
}
main.js
import { pi, greet } from './myModule'
console.log(pi)
greet("Alice")
When used in browser:
<script type="module" src="main.js"></script>
CommonJS
CommonJS is used in Node.js, Here is how CommonJS works:
const pi = 3.14159
function greet(name) {
console.log(`Hello, ${name}!`)
}
module.exports = { pi, greet }
const { pi, greet } = require('./myModule')
The differences between CommonJS and ES Modules extend beyond syntax. CommonJS loads modules synchronously, which complicates browser support, and it allows for dynamic require, making tree-shaking and static analysis more challenging.
If you're starting a new project, it's advisable to use ES Modules instead.
Bundling
While most modern browsers and runtimes support ES Modules, you might need to use a build tool like Webpack , esbuilt or Rollup to bundle your modules for older browsers.
They are pretty stright forward to get started, take esbuild as an example:
esbuild app.js --bundle --outfile=dist.js
Building processes are typically handled by frameworks or project scaffolding, so you don't usually need to worry about them.