2

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.

3
  • 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. Commented Dec 31, 2022 at 10:36
  • Try this one stackoverflow.com/questions/58211880/… Commented Dec 31, 2022 at 10:40
  • import {abc} from "./f2.js" Commented Dec 31, 2022 at 10:50

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.