Open source Node modules are very powerful as you can instantly get access to the functionality that you’d otherwise have to write yourself. Learn how to import the module once you’ve installed it.

Recently, we’ve learned how to find and install npm packages. Now let’s talk about importing them into your project and making use of them.

CommonJS modules

The default way of using npm modules in Node.js is called CommonJS. To import a module you can use the function require(id). It accepts id as a path to a module.

To require a newly installed npm module, you just pass its name as id.

const chalk = require('chalk');

Node.js will lookup for the module chalk in the node_modules folder inside the root of your project.

After the import, the constant chalk will hold all the functionality exported by the module chalk.

ES6 modules

Another approach to importing node modules is called ES6 import. Here, you’re not using the require function, but rather the keyword import. There are quite a lot of ways of using it, but the most common one is

import chalk from 'chalk';

This imports the whole module, similarly to require. If you don’t need the whole module, you can use the destructuring assignment and import only the parts of the module that you’re interested in.

import { red, blue } from 'chalk';

In this case, as described in chalk documentation you’ll only be able to use red and blue colors to color your output.

Read more JavaScript tutorials or Learn Full-Stack JS from scratch!