Split up your code into smaller, reusable pieces

Overview

ES2015 introduced built-in JavaScript modules. A module is a file containing JavaScript code and makes it easy to expose and hide certain values.

The module pattern is a great way to split a larger file into multiple smallerreusable pieces. It also promotes code encapsulation, since the values within modules are kept private inside the module by default, and cannot be modified. Only the values that are explicitly exported with the export keyword are accessible to other files.

The module pattern provides a way to have both public and private pieces with the export keyword. This protects values from leaking into the global scope or ending up in a naming collision.

In the above example, the secret variable is accessible within the module, but not outside of it. Other modules cannot import this value, as it hasn’t been exported.


Without modules, we can access properties defined in scripts that are loaded prior to the currently running script.

<html>
  <head>
    <script src="./some-module-file.js" type="module"></script>
  </head>
</html>

Node

In Node, you can use ES2015 modules either by:

  • use .mjs extention or
  • Adding "type"; "module" to your package.json.

Tradeoffs

Encapsulation

The values within a module are scoped to that specific module. Values that aren’t explicitly exported are not available outside of the module.

Reusability

We can reuse modules throughout our application

References

https://javascriptpatterns.vercel.app/patterns/design-patterns/module-pattern