Module Pattern
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 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 export
ed.
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.
Implementation
There are a few ways we can use modules.
HTML tag
When adding JavaScript to HTML files directly, you can use modules by adding the type="module"
attribute to the script
tags.
Node
In Node, you can use ES2015 modules either by:
- Using the
.mjs
extension - Adding
"type": "module"
to yourpackage.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
Exercise
Challenge
- Split the code below up into two pieces,
math.js
that includes theadd
,subtract
,divide
andmultiply
methods. Theindex.js
file contains the remaining functionality. - Use ES2015 modules to export the
add
,subtract
,divide
andmultiply
methods from themath.js
file, and import them inindex.js