I use Eclipse. I have downloaded node. The version is 12.16.3
Looking for modularization, sort of like Java classes import kind of thing. What I want to is to be able to write JavaScript code and separate them into several files. I looked at these Stack Overflow questions:
I have two files first.js and second.js. first.js should import and use a function from second.js, and then I should be able to run first.js.
Here is the code:
first.js:
import {aFunction} from "./second.js";
var firstNumber = 42;
var secondNumber = 100;
console.log(firstNumber);
console.log(secondNumber);
var answer = aFunction(secondNumber);
console.log(answer);
second.js:
export var hello = 200;
export function aFunction(numberToDouble) {
return numberToDouble * 2;
}
package.json:
{
"type": "module"
}
All three files are in the same folder. When I run first.js as node program I get this error:
C:\Program Files\nodejs\node.exe first.js
internal/modules/cjs/loader.js:1149
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\xxxx\Desktop\xxxx\xxx\first.js
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1149:13)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
code: 'ERR_REQUIRE_ESM'
}