1

I apologize if this is a basic question. I am new to JavaScript and couldn't find an answer after searching.

I am trying to run the file f1.js:

import abc from "./f2.js"

console.log(abc);

The f2.js looks like this:

export let abc = 1

When I tried to run f1.js using command node f1.js, it throw an error: SyntaxError: Cannot use import statement outside a module

I have seen other people run multiple files in html and specify type = module. My question is, can I do this without an html file and instead run it using node?

Thanks in advance.

RichS
  • 117
  • 4
  • You should have `"type": "module"` in your `package.json` which you can build yourself, or have npm do it with `npm init` although you'll probably have to edit the file and add that line yourself. – Andy Dec 31 '22 at 10:36
  • Try this one https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import – f_lap Dec 31 '22 at 10:40
  • `import {abc} from "./f2.js"` – Konrad Dec 31 '22 at 10:50

1 Answers1

1

Node.js has two module systems: CommonJS modules and ECMAScript modules.

Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader.

Source

To use import/export statements in node.js you have to use ECMAScript modules loader. In your example the simplest solution is to change the file extension to ".mjs". Additionally, as @Konrad have mentioned in the comments, you have to use brackets around "abc":

import {abc} from "./f2.js"
0Jumpero
  • 26
  • 5