0.5.1: Node Modules
Learning Objectives
Node Modules define code that can be grouped together and imported from other files
How to import and export functions from Node Modules
We can only access imported variables and variables defined in the current module
Understand the difference between named and default exports
Introduction
Node Modules (aka ES Modules) define code that can be grouped together and imported from other files. This helps clarify business logic by abstracting implementation details into separate files.
Setting up the environment:
Create a new directory named
npm_modules
Change directory to
npm_modules
Run the command
npm init -y
to initialise an npm directoryYou should see a new file has been generated, the package.json
To run the scripts you will need to alter this file as below:
Alter this file by adding in a new key and value pair.
Now you can run your scrips with node <scrip-name>
operations.js
is a Node Module that exports 2 functions: add
and subtract
.
index.js
imports add
and subtract
functions from the operations
module and uses them.
conversion.js
is a Node Module that exports functions to convert metric to US units of measurement.
index.js
imports functions from conversion
module and uses them without having to worry about implementation details.
Module Scope
Node Modules can only access variables explicitly imported or defined in their file. For example, the variable PI
in the following circleUtils
module is not accessible in index.js
because PI
is not explicitly imported or defined in index.js
.
Named vs Default Exports
There are 2 ways of exporting variables from Node Modules: named and default.
Named Exports
Named exports allow us to export 0 or more named variables from modules. This is helpful when we want to export more than 1 function from a module.
In the circleUtils
module, we export getCircleArea
and getCirclePerimeter
but not PI
.
In index.js
we can choose which named exports to import. In this case we only import getCircleArea
, but we could also import getCirclePerimeter
if we wanted.
Default Exports
Use default exports when the module only does 1 operation, and all functions in that module exist to support that operation. In general we prefer named exports for clarity of what is exported and imported. Each module can only have 1 default export.
In the calcHandScore
module, the only function that needs access externally is calcHandScore
, which we export as a default export.
index.js
imports the calcHandScore
function, allowing it to calculate the score of a card hand without having to worry about the implementation details of how to calculate it.
Note we do not use curly braces {}
when importing default exports.