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
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 .
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.
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 .
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!
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