Module building is the process of concatenating a group of modules and their dependencies into one or a group of files.
Usually the code is divided into folders and files, and external libraries need to be attached. As a result, each of these files must be included in the main HTML file in the script tag, which is then loaded by the browser.
Having separate script tags for each file means that the browser will load each file separately, which negatively affects page load speed. To get around this problem, files are combined into a single file or a pair of files to reduce the number of requests. But there remains the problem of managing dependencies between modules.
If module systems such as CommonJS or ESM are used, a tool must be used to convert them into properly organized, browser-accessible code. This is where Webpack and other bundlers come into play.
ECMAScript Modules (ESM)
Until recently, the language did not have a built-in module system. ESMs have a compact declarative syntax and the ability to load asynchronously. An ES module is a reusable piece of JS code that exports certain objects, making them available to other modules.
Each JS file stores code in a unique module context and imports the dependencies it needs and exports anything that needs to be imported by other modules. The export/import operations are implemented by the import and export constructs. There are two obvious advantages of this approach – avoiding global namespace pollution and explicitly specifying dependencies.
The new module system differs from CommonJS and others, first of all, because it is a standard. Which means it will eventually be fully supported natively by browsers, without additional tools. However, now browser support is not complete, so ESMs are used in combination with module building tools such as Webpack, Parcel and others.
Named export
A module can export multiple entities that are distinguished by their names and are called named exports. To import them into another module, we need to know the names of the exported entities we want to import.
The first way is to use the export keyword in front of all the entities to be exported. They will be added as properties to the exported entity. When importing, we will destructure the properties from the imported entity.
Default export
Often a module will export just one entity, this export is convenient for importing. The default export is the most important exported value, which can be anything: variable, function, class, etc.
Use the named export when you want to export multiple entities, and the default export when you want to export a single entity. Although it is possible to use the default export and the named export in the same file, it is good practice to select only one style for each module.