In this tutorial we’ll look at a few different ways of how to use modules in Node.js including importing and exporting function.
Let’s take a look at a common situation.
You want to separate your code into individual files to make them modular, more maintainable and reusable.
The first thing you’ll want to do is to export
your functions:
library.js
const addNumbers = (a,b) => a + b;
module.exports = {
addNumbers,
};
The above will create a new function called addNumbers
and export it for use in other files.
The key thing to look at is the module.exports
property which essentially is a property that contains an object where you define the functions (or values) you want to make available elsewhere.
To use the addNumbers
function in another file:
app.js
const lib = require('./library.js');
console.log(lib.addNumbers(2, 8));
Notice how we import the entire library.js file and then call the addNumbers
function as if it were a property of the lib
variable.
We could just as easily have destructured the addNumbers
function from the require statement.
const { addNumbers } = require('./library');
console.log(addNumbers(2, 8));
Using import/export
You might have noticed some code that makes use of the JavaScript keywords import
and export
so can we use those instead of the module.export
/ require
format.
No is the short answer.
Currently even the latest version of Node.js (14.4.0) won’t allow you to use these keywords unless you use an .mjs
suffix on both the module and import file.
However you can make use of import/export if you run your code through Babel or another transpiler.
Here’s a quick overview of how you might do that:
Install Babel into your current projec
npm install --save-dev @babel/core @babel/cli @babel/preset-env
Setup a .babelrc file
.babelrc
{
"presets": ["@babel/preset-env"]
}
Create a script to run babel
"start": "babel src --out-dir dist"
Create your source files
library.js
const addNumbers = (a,b) => a + b;
export { addNumbers };
app.js
import { addNumbers } from './library';
console.log(addNumbers(2, 8));
Compile your source files
npm run start
Run the compiled files
node dist/app.js