JavaScript·100 questions

What is the difference between CommonJS and ES modules?

Answer

In the world of JavaScript, two main module systems have historically coexisted: CommonJS and ES modules. Understanding their differences is critically important for developers, as they have fundamentally different architectures and use cases. The CommonJS system was created at the dawn of Node.js for server-side JavaScript. It uses the module.exports object to export data and the require() function to import dependencies. A typical example of such code looks like const module = require('./module'). The main technological feature of CommonJS is that it is synchronous. This means that when the require function is called, the file is fully read and executed synchronously at the moment of the call, which worked great on the server where all files are stored on a local hard drive.

On the other hand, ES modules represent the modern official JavaScript language standard, which uses the import and export keywords. Unlike its predecessor, ES modules are asynchronous by nature. The standard was designed taking into account the specifics of working in the browser, where module files can be loaded over the network with varying latency. Therefore, before executing the code, the browser or runtime environment first analyzes the dependency graph, loads all necessary modules, and only then starts their execution.

For a long time, CommonJS was the standard exclusively for Node.js backends, while ES modules were being adopted in browsers and build tools. However, the modern ecosystem has moved forward: today Node.js successfully supports both formats. Developers can use ES modules even on the server by specifying the "type": "module" field in the package.json file, or by using the .mjs file extension for files with the new syntax and .cjs for traditional CommonJS. Nevertheless, the industry's migration toward ES modules continues, as they provide better opportunities for static code analysis and optimization.

Was this answer helpful?

More questions in this topic

Related questions from other topics