To make use of the exported module and the behavior we define within it, we import the module into another file. In Node.js, use the require()
function to import modules.
For instance, say we want the module to control the menu’s data and behavior, and we want a separate file to handle placing an order. We would create a separate file order.js and import the Menu
module from menu.js to order.js using require()
. require()
takes a file path argument pointing to the original module file.
In order.js we would write:
const Menu = require('./menu.js'); function placeOrder() { console.log('My order is: ' + Menu.specialty); } placeOrder();
We now have the entire behavior of Menu
available in order.js. Here, we notice:
- In order.js we import the module by creating a
const
variable calledMenu
and setting it equal to the value of therequire()
function. We can set the name of this variable to anything we like, such asmenuItems
. require()
is a JavaScript function that loads a module. It’s argument is the file path of the module:./menu.js
. Withrequire()
, the.js
extension is optional and will be assumed if it is not included.- The
placeOrder()
function then uses theMenu
module. By callingMenu.specialty
, we access the propertyspecialty
defined in theMenu
module.
Taking a closer look, the pattern to import a module is:
- Import the module with
require()
and assign it to a local variable. - Use the module and its properties within a program.
Instructions
In 1-missionControl.js use the require()
function to import the Airplane
module from 1-airplane.js.
Recall that you will need to use the precise name of the file that contains the module.
In 1-missionControl.js, define a function displayAirplane()
. In the function, log the value of the module and its property to the console.
Call the displayAirplane()
function. In the console, you should see the name of the airplane you defined in the module.