How to use ES6 import syntax in Node.js

Published on Apr 7, 2021

3 min read

NODEJS

cover_image

Photo by Jake Weirick on Unsplash

A module is a JavaScript file that exports one or more values. The exported value can be a variable, an object, or a function.

An ES6 import syntax allows importing modules exported from a different JavaScript file. It is a common pattern to use modules across React and React Native applications. The syntax is composed of the following ES module standard:

1import XXX from 'xxx';

An ES module is the ECMAScript standard of working with modules. Node.js uses the CommonJS standard to import modules. The syntax for this type of standard can be described as:

1const XXX = require('xxx');

Node js doesn’t support ES6 import directly. Try writing the import syntax in a JS file:

1// index.js
2
3import { ApolloServer, gql } from 'apollo-server';

Run the Node.js server either by using npm start or npm run dev and you will encounter the following error:

ss1

The solution to this error is in the first line of the above error snippet and is now a recommend way by Node.js. Set the "type": "module" in package.json file.

1{
2 "type": "module"
3}

This solution works for the latest Node.js versions (which is 15.4.x at the time of writing) and versions above 14.x.x.

ss2

What about environments using Node version lower than 14

🔗

Another solution to this problem is to use Babel. It's a JavaScript compiler and allows you to write JS using the latest syntax. Babel is not framework or platform opinionated. This means that it can be used in any project that is written in JavaScript and thus, in a Node.js project as well.

Start by installing the following dev dependencies from a terminal window:

1npm i -D @babel/core @babel/preset-env @babel/node

Then create a file at the root of the Node.js project called babel.config.json and add the following:

1{
2 "presets": ["@babel/preset-env"]
3}

The package @babel/node is a CLI utility that compiles JS code in a Node.js project with Babel presets and plugins before running it. It means it will read and apply any configuration mention in babel.config.json before executing the Node project.

Replace the node with babel-node to execute the server in the start or dev scripts.

An example of running Node server using npm run dev script:

1{
2 "scripts": {
3 "dev": "nodemon --exec babel-node server.js"
4 }
5}

Share this article on Twitter


More Posts

Browse all posts

Join 1300+ devs & subscribe to my newsletter!

NEWSLETTER

🔗 Subscribe on Revue

AMAN MITTAL author

Software Developer and Technical Writer since 2017. Loves learning and writing about Node.js, React, React Native & Expo. Previously, a Developer Advocate at Draftbit.


Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.