Common JS versus ES Modules


Uncategorized

Updated May 18th, 2023

Common JS versus ES Modules seems more complicated then necessary.

Environment

CommonJS modules are typically used in Node.js applications.

ES modules are popular in browser-based applications because they can be loaded asynchronously and don’t require an underlying runtime environment like Node.js

CommonJS Examples

exports.function = () => {}
const whatEv = require("../pathToFile")

But you will also see the following syntax

module.exports = {yourThing}

So why the difference between exports and module.exports?

From the stack overflow article referenced there are two difference between “exports” and “module.exports”

1.) We use module.exports for a single class, variable or function from one module to another module. We use “exports.yourthing” for multiple variables or functions from one module to another.

2.) module.exports is the object reference that gets returned from the require() calls. But “exports” is not returned by require().

ES Module Examples

Export as default

// one way is to export as default
const Home = () => {}
export default Home
// and corresponding import syntax
// notice no curly brackets
import Home from "../pathToFile"

Note you could also export as default in one line:

export default const Home = () => {}

Sources

Some straightforward explanations here

KnowledgeHut article here

Stack Overflow article from a decade ago here