将JavaScript类导入另一个类时出现意外标识符{classname}

jre*_*enk 5 javascript import node.js

我正在使用Node v10.11.0,并且正在从Ubuntu 18.04运行此脚本。

我的文件设置如下所示:

main.js

import Login from './Login.mjs';

class Main {
    constructor() {
        const login = new Login();

        login.login();
    }
}

new Main();
Run Code Online (Sandbox Code Playgroud)

Login.mjs

import readline from 'readline';

class Login {
    constructor() {
        this.username = '';
        this.password = '';
        this.readline = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
    }

    login() {
        this.readline.question('What is your username?', answer => {
            this.username = answer;
        });

        this.readline.question('What is your password?', answer => {
            this.password = answer;
        });
    }
}

export default Login;
Run Code Online (Sandbox Code Playgroud)

main.js使用以下命令调用:

node --experimental-modules main.js
Run Code Online (Sandbox Code Playgroud)

这导致以下错误:

(node:7280) ExperimentalWarning: The ESM module loader is experimental.
/home/jrenk/Workspace/bitefight/main.js:1
(function (exports, require, module, __filename, __dirname) { import Login from './Login.mjs';
                                                                 ^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Proxy.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js 
    (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at createDynamicModule (internal/modules/esm/translators.js:56:15)
    at setExecutor 
    (internal/modules/esm/create_dynamic_module.js:50:23)
Run Code Online (Sandbox Code Playgroud)

^^^^^下的所属Login,但我似乎无法得到它格式化这里的问题。

我也尝试保存Login.mjsas Login.js并调用main.js不带as的方法,--experimental-modules但这会导致完全相同的错误。

这个问题类似于这个问题。正如我上面所说,我已经尝试过那里描述的内容,但是没有运气。

Est*_*ask 4

原生 ES 模块(importexport语句)只能在 Node.js 中的 .mjs 文件中使用。为了使用它们,入口点应该命名为main.mjs

为了在 .js 文件中使用 ES 模块,ES 模块应该被转译为回退到,或者与自定义 ES 模块加载器require一起本地使用。由于后者不是 Node.js 的原生行为,因此根据经验,不能推荐它。