close

[Solved] SyntaxError: Cannot use import statement outside a module in nodeJs

Hello Guys, How are you all? Hope You all Are Fine. Today When I run my index.js file and suddenly I get the following error in my stack track SyntaxError: Cannot use import statement outside a module in nodejs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How SyntaxError: Cannot use import statement outside a module in nodeJs Error Occurs ?

When I run my index.js file and suddenly I get the following error in my stack track

SyntaxError: Cannot use import statement outside a module

Here is my Index.js file

require('dotenv').config()
import {startServer} from './server'

How To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error ?

  1. How To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error ?

    To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error Open Your package.json file. Just add the top-level “type” field with a value of “module” This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension. add “type”: “module” in the upper level as show below.

  2. SyntaxError: Cannot use import statement outside a module in nodeJs

    To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error Open Your package.json file. Just add the top-level “type” field with a value of “module” This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension. add “type”: “module” in the upper level as show below.

Solution 1: Add “type”: “module” to your package.json

  1. Open Your package.json file.
  2. Just  add the top-level "type" field with a value of "module"
  3. This will ensure that all .js and .mjs files are interpreted as ES modules.
  4. You can interpret individual files as CommonJS by using the .cjs extension.
  5. add "type": "module" in the upper level as show below:
// package.json
{
  "name": "my-project",
  "version": "0.0.0",
  "type": "module",
  "scripts": { ...
  },
  ...
}

Solution 2: Change module to commonjs

If you are facing issue with Typescript then just change

    "module": "esnext",

to

    "module": "commonjs",

Solution 3: Change .js files extension to .mjs

  • Change .js files extension to .mjs
  • Add –experimental-modules flag upon running your app.
  • Optional: add “type”: “module” in your package.json

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also Read

Please Rate Our Solution to Motivate Us For Give Our Best

Leave a Comment