We can get started with modules by defining a module in one file and making the module available for use in another file with Node.js module.exports
syntax. Every JavaScript file run in Node has a local module
object with an exports
property used to define what should be exported from the file.
Below is an example of how to define a module and how to export it using the statement module.exports
.
In menu.js we write:
let Menu = {}; Menu.specialty = "Roasted Beet Burger with Mint Sauce"; module.exports = Menu;
Let’s consider what this code means.
let Menu = {};
creates the object that represents the moduleMenu
. The statement contains an uppercase variable namedMenu
which is set equal to an empty object.Menu.specialty
is defined as a property of theMenu
module. We add data to theMenu
object by setting properties on that object and giving the properties a value."Roasted Beet Burger with Mint Sauce";
is the value stored in theMenu.specialty
property.module.exports = Menu;
exports theMenu
object as a module.module
is a variable that represents the module, andexports
exposes the module as an object.
The pattern we use to export modules is thus:
- Create an object to represent the module.
- Add properties or methods to the module object.
- Export the module with
module.exports
.
Let’s create our first module.
Instructions
Let’s begin by implementing the pattern above in an example. In 1-airplane.js create an object named Airplane
.
Within the same file, add a property to the Airplane
object named myAirplane
and set it equal to "StarJet"
.
Export the module.