The error ‘cannot use import statement outside a module’ is self-explanatory, which means it is the error that occurs when you attempt to use an import statement outside of a module such as in the global scope of a script or inside a function.
The above error occurs in Python usually when your import statements are placed inside the appropriate functions or methods
When writing Python code, it’s important to understand the difference between a script and a module. A script is a standalone file that can be executed directly, while a module is a file that can be imported and used by other scripts or modules.
To solve the above ‘cannot use import statement outside a module’ error, you should ensure that you are working with the module file rather than the script file. Forwardly, your import statements are placed inside the appropriate functions or methods.
Additionally, make sure that your file has a .py extension, as Python will only recognize files with this extension as modules.
You can learn about Python basics here
- Change the file extension of your script file to .mjs to tell Node.js to treat the file as a module.
- Use the –experimental-modules flag when running your script to enable support for ES modules in Node.js. For example:
node --experimental-modules your_script.js
Once you are running your code in a module environment, you should be able to use the import statement to import other modules into your script.
Hope in the both cases ‘cannot use import statement outside a module’ error would be solved.