The modules is the last core concept in JavaScript we must discuss before moving on to more practical problems. After this lesson, we are going to discuss how JavaScript works in a web application, as both the frontend and the backend.
So far, all of the examples we've seen can be placed in one single JavaScript file, but as your application gets bigger, that will put a lot of pressure on future maintenance. It is better to split your application into multiple files based on their specific purposes or functionalities. These files are called modules.
A module may contain classes, functions, objects, variables, and so on. These resources should be exported, so that they can be imported into the files that depend on them.
A brief history
The module system for JavaScript has been missing for a long time. Because initially, JavaScript was just designed to build small scripts that run in the browser, there wasn't need for a module system. But later, the language evolved into something much more powerful.
In 2015, a built-in module system was still missing in JavaScript, but people were already building large-scale applications with it. The solution back then was CommonJS. A CommonJS module is loaded with the function require()
.
1const module = require("package");
Later, a new module system was introduced to the JavaScript standard called ES Modules, which allows you to import modules using the keyword import
.
1import { module } from "package";
Their main difference is that CommonJS modules are loaded synchronously. Because require()
is just a standard function, it is executed where it is placed in the file. However, for ES Modules, JavaScript will analyze all the import
statements first, and the modules will be loaded asynchronously, allowing better optimizations.