Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use import statement outside a module

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");     } } 
like image 627
Walter Dudley Avatar asked Oct 12 '19 19:10

Walter Dudley


People also ask

Can we use import statement outside a module?

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.

Can't use import statement outside a module TypeScript?

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 .

Can I use import in 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.


1 Answers

Add files with type="module":

<script src="file1.js" type="module" ></script>
like image 189
marzelin Avatar answered Oct 05 '22 09:10

marzelin