【问题标题】:Unexpected Identifier {classname} when importing JavaScript Class into another Class将 JavaScript 类导入另一个类时出现意外标识符 {classname}
【发布时间】:2019-03-11 16:05:00
【问题描述】:

我正在使用 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();

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;

我正在使用以下命令调用main.js

node --experimental-modules main.js

这会导致以下错误:

(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)

^^^^^ 属于 Login,但我似乎无法在问题中将其格式化。

我还尝试将Login.mjs 保存为Login.js 并在没有--experimental-modules 的情况下调用main.js,但这会导致完全相同的错误。

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

【问题讨论】:

  • 难道他们都必须是.mjs - 至少,那些使用The ESM module loader的人

标签: javascript node.js import


【解决方案1】:

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

为了在 .js 文件中使用 ES 模块,应该将 ES 模块转译为回退到 require,或者与 custom ES module loader 本机一起使用。由于后者不是原生 Node.js 行为,因此不能作为经验法则推荐。

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 2021-06-01
    • 2019-12-23
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多