I'm trying to use classes in pure JavaScript, so I'm facing the error "Uncaught SyntaxError: Cannot use import statement outside a module" and can't solve it.
File1.js - Main file
import example from "./file2"; var test = new example();
File2.js - Class file
export default class example { constructor() { console.log("hello world"); } }
The "Cannot use import statement outside module" error also occurs if you are trying to run your source files which contain ES6 module import / export syntax, instead of running your compiled files from your build directory. Make sure to run your compiled files from your build/dist directory only.
To solve the error "Cannot use import statement outside a module" in TypeScript, set the module option to commonjs in your tsconfig. json file and make sure to compile your TypeScript files (e.g. with ts-node ), and not to run them directly with node .
NodeJS allows us to import CommonJS modules from ES Modules. If we would like to import our CommonJS class export example from above, our ES Module import would look like this: // index.
Add files with type="module"
:
<script src="file1.js" type="module" ></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With