How to fix the cannot use import statement outside a module error in nodejs?

Introduction

While working with node.js, you may face the cannot use import statement outside a module error in nodejs. This error appears when you use the “ES modules” syntax in a file that Node.js treat as a CommonJS module by default. Here are two methods that can solve the cannot use import statement outside a module error in nodejs”

Methods

  1. Enabling ES Modules
  2. Converting to CommonJS Syntax

1) Enabling ES Modules:

In this method, you can enable the ES module by changing the javascript file from “header.js” to “header.mjs”. After changing the name Node.js will treat the file as an ES module. Now open the package.json file and add the following line:

{
  "type": "module"
}

Now you need to save the changes and replace the “require” statements

const express = require('express');

with import statements as shown below:

import express from 'express';

2) Converting to CommonJS Syntax:

We can convert the ES module to common javascript syntax by replacing the “Import” statement that is given below:

import express from 'express';

with “require” statement:

const express = require('express');

Now you are using the commonJS syntax so keep the file name “header.js”

Conclusion:

Both methods are straightforward you can use the one method which you prefer to avoid the cannot use import statement outside a module error in nodejs.

Similar Posts