简体   繁体   中英

Make minimal working JavaScript code with import and export

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'
}

Node 12.x comes with es6 modules behind the feature flag --experimental-modules

you either have to add it to your start directive in your package.json to get a npm start shortcut or switch to the current stable version wich ships with es6 modules out of the box.

i also suggest renaming the javascript files to.mjs to stay in convention. in future you can use.mjs and.cjs to switch between modules and common legacy code.

more on that in the official documentation: https://nodejs.org/api/esm.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM