. Advertisement .
..3..
. Advertisement .
..4..
The “Typescript: Cannot Use Import Statement Outside A Module” will appear during you are operating with Node.js, or react applications. We will summarize every case and the solution with illustrated examples.
When does “Typescript: Cannot Use Import Statement Outside A Module” happen?
This error occurs when you are loading the script without using the type = “module” attribute.
SyntaxError: Cannot Use Import Statement Outside A Module
Here are the root causes of this error “Typescript: Cannot Use Import Statement Outside A Module”.
1. You have forgotten to set “module type” to “commonjs”.
2. You are loading the script from the src directory.
How to solve this problem?
Approach 1: Use type= “module” and add to package.json
When you are using import statements rather than requiring to load modules, you have to make sure that the package.json gets a: type= “module”.
{
// ...
"type": "module",
// ...
}
Fundamentally, using “type”: “module” and adding to package.json can let you know you are using ES modules that might handle the error.
Then, you edit the tsconfig.json file and transform the module property to “commonjs.
ts.config
"target": "esnext",
"module": "esnext",
To:
ts.config updated
"target": "esnext",
"module": "commonjs",
Until the moment, this error is troubleshot successfully.
Approach 2: Add type= “module” into the script tag
You just tackle the error by using and adding a type= “module” attribute into the script below.
<script type="module" src="some_script.js"></script>
Now, check the result, and the error “Typescript: Cannot Use Import Statement Outside A Module” is solved rapidly.
Approach 3: Use “Import” and require statements
As for other cases, you need to use “Import” and require statements to tackle this error.
import { parse } from 'node-html-parser';
parse = require('node-html-parser');
Note: while you are loading modules, if you face the ReferenceError: require is not defined, you should use the “import syntax”.
Conclusion
That’s all about the error “Typescript: Cannot Use Import Statement Outside A Module” and related solutions that you should focus on so far. You can leave your feedback below if needed.
Read more:
→ Property Does Not Exist On Type Object In TypeScript: Cause And Solutions
Leave a comment