0

I am trying to do an import from one file to another in VSCode. My two files are as follows:

// file2.js
const Name1 = "Bob";
const Name2 = "Sarah";

class Person {
    constructor(name) { this.name = name; }
    greet() { console.log('Hello,', this.name); }
}

export {Name1, Name2, Person};
// file1.js
import { Name1, Name2, Person } from "./file2.js"
p = new Person(Name1);
p.greet();

However, I get the following error from VSCode / Node:

import { Name1, Name2, Person } from "./file2.js"
SyntaxError: Cannot use import statement outside a module

What does that mean exactly (why isn't the file considered a module?), and how would I properly fix that to do a valid import?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

0

it's a problem because of using require or import as your style, as well as how you invoke your node/js. if you want to use imports, then you need to have your JS code in .mjs files, change your config.json to include "type": "module", and then you can do this. or simply use require if you prefer not to go the EMCMA6 route.

G-Force
  • 345
  • 3
  • 10
0

Here is a full example:

// folder structure
test_import/
  - file1.js
  - file2.js
  - package.json
// file1.js
import { Name1, Name2, Person } from "./file2.js"
let p = new Person(Name1);
p.greet();
// file2.js
const Name1 = "Bob";
const Name2 = "Sarah";

class Person {
    constructor(name) { this.name = name; }
    greet() { console.log('Hello,', this.name); }
}

export {Name1, Name2, Person};
// package.json
{
  "type": "module"
}

In other words, just add a json file named package.json -- or do npm init with the"type": "module" entry.

David542
  • 104,438
  • 178
  • 489
  • 842