Using ES modules with CommonJS modules in the browser

Matt Lim
2 min readAug 18, 2020

--

This is not meant to be a comprehensive overview of ES modules and CommonJS modules — I do not go into depth about what modules are and how they work. Rather, it is meant to highlight the differences between ES modules and CommonJS modules and how you can use them together.

This is part one of a four part series.

  1. The three differences between require and import in JavaScript
  2. Using ES modules using CommonJS modules in Node.js
  3. Using ES modules using CommonJS modules in the browser
  4. Using ES modules using CommonJS modules with webpack

Check out full code examples here: https://github.com/arcticmatt/javascript_modules/tree/master/browser.

Mixing ES modules and CommonJS modules

This topic is a bit misleading, because the browser doesn’t have built-in support for CommonJS modules. That is, there is no built-in require function, and there is no global exports object that you can add exported variables and functions to.

So, without using any additional libraries, the compatibility chart looks like this:

You could download one of these libraries to use CommonJS modules in the browser, in which case this chart would look different. In reality though, you’ll probably be using webpack to bundle and transpile your JavaScript code before it runs. That’s what the fourth post talks about.

--

--

Matt Lim

Software Engineer. Tweeting @pencilflip. Mediocre boulderer, amateur tennis player, terrible at Avalon. https://www.mattlim.me/