A module is just a file. One script is one module. As simple as that.

Using the keywords “export” and “import,” we can move code (function, variable) from one module to another, dividing a large script into manageable modules. We use “export” keyword for code in module that needs to be used outside of module. we add code from other modules to a module by using import keyword. there are two main types of import and export in js.

  1. named import
  2. default import
Feature Named Exports Default Export
Syntax export { name1, name2 ... }; export default something;
Import Syntax import { name1, name2 ... } from './module.js'; import anyName from './module.js';
Number Multiple per module Only one per module
Use Case Exporting a collection of related functions/values Exporting the main "thing" from a module
Flexibility Less flexible imports (names must match) More flexible imports (any name can be used)
Best Practice When you have many values to export When you have one primary value to export

Some facts for modules

  1. always “use strict” - module code is by default in strict mode without explicitly writing “use strict” on top of module
  2. module level scope - Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts.
  3. A module code is evaluated only the first time when imported - If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers.
  4. in a module “this” is undefined - In a module, top-level this is undefined. Compare it to non-module scripts, where this is a global object

Don’t be afraid to import too much

Modern build tools, such as webpack and others, bundle modules together and optimize them to speedup loading. They also remove unused imports.

For instance, if you import * as library from a huge code library, and then use only few methods, then unused ones will not be included into the optimized bundle.