Split up your code into smaller, reusable pieces
The module pattern is a great way to split a larger file into multiple smaller, reusable 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
Without modules, we can access properties defined in scripts that are loaded prior to the currently running script.
With modules however, we can only use the values that have been exported.
There are a few ways we can use modules.
type="module" attribute to the
In Node, you can use ES2015 modules either by:
- Using the
"type": "module"to your
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
- Split the code below up into two pieces,
math.jsthat includes the
index.jsfile contains the remaining functionality.
- Use ES2015 modules to export the
multiplymethods from the
math.jsfile, and import them in