- [Instructor] Every JavaScript file is a module.
We've been loading modules with the require function,
and the require function is part
of that common JS module pattern,
but it only represents half of the pattern.
The half that loads the modules.
The other half of the pattern is module.exports
or the mechanism by which we make our modules consumable.
The first thing I'll do here in 03_04's start
is I'm going to create a file called myModule.js,
and in it we're going to create a few variables.
So we're going to create a count variable.
We'll set that equal to zero and a few different functions.
So the first we'll be for incrementing,
and this is going to increment our count,
add one to our count, and then we'll
also create a decrement function
that is going to do the opposite.
So --count will remove one,
then we'll create this getter function
that's going to get whatever the most recent count is.
Perfect, so now what I can do is
I'm going to export all of this.
Module.exports. We will say anything is true.
Who is Bill.
We'll export the count, the incrementer function
the decrementer function and getCount.
Perfect, so now all of these values
can be consumed by a different file.
This other file is going to be called.
Let's create it now, app js, and this is going
to be responsible for consuming everything else.
So we'll say const myModule = require,
myModule.
So we're importing this JavaScript file
from the same directory.
Now if we say console log,
myModule.anything.
Okay, so let's go ahead and run this.
We're going to say node app, and this will return true.
Similarly, I could say myModule.inc.
This is going to return one.
So we've incremented that count,
and we should be able to return it.
Nice, another way that we could import these files is
that we could import them instead
of importing the entire module.
We could say let's require the incrementer,
the decrementer and the getCount function,
then if we call these functions a few different times.
So we'll say inc, inc, inc, add one,
then we could say console log, "the count is," getCount.
Call the function inside of the template string, run it,
and we should see that the count is three
'cause I've used this a few different times.
So we can break our code up
into separate files called modules.
All of the variables in each file are scoped to that module.
Everything that we are going to export
can be consumed by a different file.
Modules make our code reusable and consumable
because we can publish our modules to NPM
and share them with the rest of the community.