Use Import Instead of Require in Node App

How to Use Import Instead of Require Statements in a Node App

By Brian Francis

July 12th, 2021

Thanks to the support of ESM files in Node.js, the days of using const something = require('something') are a thing of the past. Let’s learn how easy it can be to switch to using **import statements **in your new Node,js projects.

Today we will be making a very simple Express API to demonstrate how modern import syntax can be implemented in vanilla NodeJS apps.

Pre-Requisites

  • Basic Understanding of NodeJS

  • Knowledge of Express is not a requirement, but will certainly be helpful

  • Beginner Level Command Line Experience (know how to make a new directory and change to it)

  • An up to date version of node (Versions 12 and 14 which are the current LTS versions of node at the time of writing this article support this feature)

Let’s Get Started

We are going to be building an Express API that accepts one route. This route will live at /hello and this is going to return a string that says “hello world”. Without further ado, let’s get coding.

The first thing that we are going to do is open up a terminal/PowerShell (depending on your operating system) and navigate to the directory that you would like to put your code in. I have a code directory at the root of my machine that I put all my projects in, but any old directory will work fine. After you have gotten to the directory of your choice, run this command.

mkdir esm-modules

And then navigate to it in the command line with this.

cd esm-modules

Once inside the directory, you will want to run this command.

npm init -y

This will create an empty Node project.

Now run this command to install Express in your Node app.

npm i express

Go ahead and open up your package.json and add a line somewhere inside of the JSON object that says this. This is what will be allowing us to use import/export statements so this is very important.

"type": "module"

It should look something like this after you have edited it.

Noting that the version number for express may vary depending on when you read this article.

With all this in place, we can now use import/export statements freely in our NodeJS app.

We are going to be creating an app.js file in the route of our project and adding the following code to it.

With this code now added, everything should work. You can go ahead and run the following command in the command line.

node app.js

After the app compiles, you should be able to go to your browser and navigate to the following URL:

http://localhost:3000/hello

Wrapping Up

And that’s really it. You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.



Continue Learning