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

2024-03-21

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

登录.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)

The ^^^^^属于Login但我似乎无法在问题中对其进行格式化。

我也试图挽救Login.mjs as Login.js并调用main.js没有--experimental-modules但这会导致完全相同的错误。

这个问题类似于这个问题。 https://stackoverflow.com/q/50792976/4011778正如我上面所说,我已经尝试过那里描述的内容,但没有运气。


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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 JavaScript 类导入另一个类时出现意外的标识符 {classname} 的相关文章

随机推荐