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.
Contents
How to Fix SyntaxError: Cannot use import statement outside a module in nodeJs Error?
- 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. - 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 yourpackage.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
- Composer detected issues in your platform: Your Composer dependencies require a PHP version “>= 7.3.0”
- npm does not support Node.js v10.19.0 You should probably upgrade to a newer version of node as we can’t make any promises that npm will work with this version
- A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
- remote: Bitbucket Cloud recently stopped supporting account passwords for Git authentication
- pip is configured with locations that require TLS/SSL however the ssl module in Python is not available