Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: SyntaxError: Cannot use import statement outside a module

I am getting this error SyntaxError: Cannot use import statement outside a module when trying to import from another javascript file. This is the first time I'm trying something like this. The main file is main.js and the module file is mod.js.

main.js:

import * as myModule from "mod"; myModule.func(); 

mod.js:

export function func(){     console.log("Hello World"); } 

How can I fix this? Thanks

like image 248
Serket Avatar asked Jun 20 '20 16:06

Serket


People also ask

How do you fix a Cannot use import statement outside a module on node?

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 .

What is require () in JavaScript?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do I use require instead of import?

The major difference between require and import , is that require will automatically scan node_modules to find modules, but import , which comes from ES6, won't. Most people use babel to compile import and export , which makes import act the same as require .


1 Answers

In order to use the import syntax (ESModules), you need to add the following to your package.json at the top level:

{     // ...     "type": "module" } 

If you are using a version of Node earlier than 13, you additionally need to use the --experimental-modules flag when you run the program:

node --experimental-modules program.js 

Hope it helps!

like image 92
Achraf Ghellach Avatar answered Sep 19 '22 08:09

Achraf Ghellach