close

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

Today We are Going To Solve SyntaxError: Cannot use import statement outside a module in nodeJs in nodejs. Here we will Discuss All Possible Solutions and How this error Occurs So let’s get started with this Article.

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

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

    To Fix SyntaxError: Cannot use import statement outside a module in nodeJs Error just Change the module. To solve this error you have to change the module from esnext to commonjs In your tsconfig.json.. just try this like given below:
    "module": "esnext", to "module": "commonjs", By doing this you will solve your error.

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

    To Fix SyntaxError: Cannot use import statement outside a module in nodeJs Error just Add --experimental-modules flag. Here you have o change .js files extension to .mjs. and after it just add --experimental-modules flag upon running your app and just add the "type": "module" in your package.json. By doing this you can get rid of this error.

Solution 1 : Change the module

To solve this error you have to change the module from esnext to commonjs In your tsconfig.json.. just try this like given below:

 "module": "esnext",

to

"module": "commonjs",

By doing this you will solve your error.

Solution 2 : Add --experimental-modules flag

Here you have o change .js files extension to .mjs. and after it just add --experimental-modules flag upon running your app and just add the "type": "module" in your package.json. By doing this you can get rid of this error.

Solution 2 : Run the commands

when someone cannot add "type": "module" and cannot not solve the error by adding that then this method will be useful for you.

To solve this error just run the below command first

npm i esm --save

Then for package.json you can run the below command:

  "scripts": {
    "start": "node -r esm src/index.js",
  }

And at the last just run this command. By doing this you will solve your problem.

nodemon --exec npm start

Conclusion

So these were all possible solutions to this error. I hope your error has been solved by this article. In the comments, tell us which solution worked? If you liked our article, please share it on your social media and comment on your suggestions. Thank you.

Also Read This Solutions

Leave a Comment