Professional Documents
Culture Documents
Basics of Modular Javascript: Intended Audience
Basics of Modular Javascript: Intended Audience
Intended Audience
This article is for those just being introduced to JavaScript. When I was first
introduced to it, I had a lot of questions about what the difference was
between ECMA and JS, transpilers and bundlers, and on webpack itself. I
couldn’t quite wrap my head around all of it. Then I found a course on
PluralSight that explained Modular JavaScript flawlessly. But there are two
problems. One is that Pluralsight is expensive and although I love their
courses, the average student or new hire can’t exactly afford a subscription
quite yet. Two, not a lot of people have time to watch a 2+ hour course
online. So, summarize here are my learnings and my newfound
understanding of the basics in modular JavaScript. I hope it helps someone.
1 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
its earlier version such as ES5 contained many limitations that prohibited
creating classes, importing modules, etc. The first standardized version of
JavaScript was referred to as ES5. The newest version today is referred to as
ES6/ECMAScript 2015/ES2015; this is the very first update to the language
since it was standardized in 2009. ES5 originally didn’t include support for
modules. To understand why this is important, we need to understand why
developers need modules and what they give us.
2 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
Code Extensibility
. . .
Vanilla ES5
Sometimes you are constrained to using plain vanilla ES5 JavaScript and
cannot use any third party libraries that support modularity or even ES6. In
this case, there are two common patterns in JS to implement modules but
they have positives and negatives.
Singleton Pattern
The singleton pattern takes advantage of what we called immediately
invoked function expressions, commonly known as an IIFE. JavaScript has
3 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
function level scope so all variables and functions declared within the
function expression are not available in the global scope. The only thing in
the global scope will be the name we choose to give to the function
expression, if we choose to give it one ( we can use an anonymous function
and avoid giving it a name at all). In our case, we will assign a variable
name to a function expression which will be immediately invoked, leaving
the return value of that function to be assigned to the variable we choose.
are available in the global namespace but the variable scoreboard is.
function printMessage() {
console.log(message);
function updateMessage(newMessage) {
message = newMessage;
return {
4 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
showMessage: printMessage,
updateMessage: updateMessage
To access the scoreboard module in another file, we just simply access the
member variables that we specified in the object returned by the scoreboard
function.
scoreboard.printMessage();
As you can see in the above example, it doesn’t matter what I call the
object’s members in my returned object, all that matters is that they are
assigned the value of their respective functions in order to have the correct
implementation. We also have used an immediately invoked function
definition. We want to immediately invoke the function expression assigned
to the scoreboard variable so that the return value is assigned to the
scoreboard variable and can be used without invoking any function later on.
Constructor Pattern
Another pattern that you may see is called the constructor pattern. The
main difference between this pattern and the singleton pattern is that this
function expression is no longer immediately invoked and instead must be
explicitly invoked when you wish to use the variable or module in our case.
5 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
function printMessage() {
console.log(message);
return {
printMessage: printMessage
};
/* no longer immediately executing the function -- function
definition is assigned to a variable which must later be
invoked. */
myScoreboard.printMessage();
Key Takeaways
These patterns are extremely useful when you are constricted to using
plain old vanilla ES5
6 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
. . .
The two most popular modular formats are CommonJS and AMD. There
are different reasons for choosing one or the other but we won’t get into
that here. Another module format you might see often is called UMD. The
two most popular loaders are RequireJS, which is most commonly used to
load AMD modules, and SystemJS which supports many different module
formats. We will now look at two different combinations of the most
popular module formats and loaders, but keep in mind, there are many
other combinations to be made.
In quick summary:
7 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
8 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
define([], function() {
return {
addResult: addResult,
updateScoreboard: updateScoreboard
});
Where we pass in the file path to dependencies as an array into the first
parameter (leaving off the .js extension), and the function body is still the
second parameter taking in our specified dependencies as parameters.
In order for our browsers to be able to interpret this sort of code, we would
use a loader like RequireJS. You can go through the following steps to install
RequireJS
9 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
bower-requirejs
function addResult(newResult) {
results.push(newResult);
}
function updateScoreboard() {
...
}
//a little bit different way of doing it than the player module
module.exports = {
addResult: addResult,
updateScoreboard: updateScoreboard
10 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
};
And to include our new scoreboard module in another file, we would use
the require function defined by the CommonJS syntax. This function takes
in a javascript file that another file may depend on. It will import the
module and assign it to the variable scoreboard.
scoreboard.addResult(result);
systemjs
2. Import the SystemJS library into our html with a script tag. Then,
configure SystemJS in either in a separate JavaScript file or in our html.
We can include it in our html in between script tags like so:
11 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
<script>
// configure systemJS
System.config({
meta: {
format: 'cjs' //cjs refers to CommonJS format
}
});
</script>
System.import tells the loader where to begin loading JS files. Our import
statement specifies that the root module is app.js which requires the use of
all our other modules but is not a dependency itself. format: 'cjs' tells the
config that we are loading the commonJS format.
Key Takeaways
Module formats and loaders give you the ability to manage your
dependencies. This means you can specify what files depend on what
modules before hand.
. . .
Modules in ES6
12 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
. . .
Modules in ES6
Modules in ES6 are very simple to use. Like other usage of modules, ES6
provides a way to export modules so that they can be specified as
dependencies to other modules.
Exporting Modules
There is more than one way to export modules in ES6.
13 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
Importing Modules
There are also different syntaxes you can use to import modules in
JavaScript once they have been exported. Below are a few examples of how
we would import the modules exported above.
scoreboard.updateScoreboard();
14 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
We can also rename the properties we import from modules by using the
keyword. And we can specify which properties to import instead of
importing everything contained within the player module. So the above
import statement, would give us a function called getPlayerName which
references the function getName in player.js and a function called logPlayer
which references the logPlayer function in player.js. Since we have not
specified a name for our module, we can simply call the functions like this
from the game module:
function printGame() {
logPlayer();
. . .
Transpilers
With the advent of modules in ES2015, we now don’t need to use any third
party libraries to create modular JavaScript code. Unfortunately, modern
day browsers don’t support ES2015 code quite yet, which means our user’s
browsers cannot render the code we write in the newest version of JS. The
solution to this has been transpilers. This word may sound similar to a
15 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
preset s es2015 — — out-dir build The out-dir will specify where to put
our transpiled JavaScript. Babel should tell you the destination of where
the transpiled code went.
Bundlers
A bundle by definition is several objects bound together, thereby making a
bundler a type of machine that does that binding. In JavaScript, a bundler
does just that. It takes a group of JavaScript files together and binds them
into a single JavaScript file. When we bind multiple JS files together, then
there are less dependencies to load at startup time. Instead of loading 12
different javascript files for one HTML page, we can instead bundle them
together and load just a single one when we load the page. But beware of
16 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
When we bundle too many files together at once, loading that one bundled
file can take so long it will interrupt the user’s experience instead of making
it smoother.
3. Make a directory which you want the bundled files to be held in such as
build or bundledJS
Webpack
Sometimes using these old Javascript formats and having a large amount of
JavaScript code can get overwhelming. Every time you bundle your JS, it
17 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
generates another file you need to include in your HTML and on top of
transpiling them with babel, things can get confusing. So in order to solve
this problem, Webpack has evolved to do everything at once. Webpack is a
tool that does bundling, transpiling and a lot more by running a single
command.
What Figure 1 shows, is how webpack will take modules with dependencies,
even css files and images, and bundle them into static assets we can include
in our HTML code. So how exactly does webpack do this?
18 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
Uses a regex expression to choose what files to run through the loader
module.exports = {
output: {
},
module: {
loaders: [{
query: {
}]
19 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
};
Ta da! It is that simple. With this config file, you can simply run webpack
from its location (for me that would be in the node_modules directory):
./node_modules/.bin/webpack
Then an output file is generated in the build directory, called bundle.js and
I can include this file with one line in my HTML like so:
Key Takeaways
20 of 21 3/13/20, 4:56 AM
Basics of Modular JavaScript - Christine Rohacz... https://medium.com/@crohacz_86666/basics-of...
Webpack can transpile and bundle JavaScript files for your, supporting
dependency management and module clusters
References
The above code examples and most of the information were taken from a
PluralSight course called ‘JavaScript Modules’. I do not claim to have come
up this the code example on my own. This course gave me a lot of the
information that I needed to learn all about modules in JavaScript. It is a
highly recommended course, a long with many others PluralSight has to
offer.
21 of 21 3/13/20, 4:56 AM