Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Identifier {classname} when importing JavaScript Class into another Class

Tags:

I'm using Node v10.11.0 and am running this script from Ubuntu 18.04.

My file setup looks like this:

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;

I'm calling the main.js with the following command:

node --experimental-modules main.js

This leads to the following error:

(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 ^^^^^ belongs under the Login but I can't seem to get it formatted right here in the question.

I also tried to save the Login.mjs as Login.js and calling the main.js without the --experimental-modules but this leads to the exact same error.

This question is similar to this question. As I said above I already tried what is described there but no luck.

like image 730
jrenk Avatar asked Oct 06 '18 09:10

jrenk


1 Answers

Native ES modules (import and export statements) can only be used in .mjs files in Node. In order to use them, entry point should be named main.mjs.

In order to use ES modules in .js files, ES modules should either be transpiled to fall back to require, or used natively with custom ES module loader. Since the latter isn't native Node.js behaviour, it cannot be recommended as a rule of thumb.

like image 159
Estus Flask Avatar answered Oct 14 '22 09:10

Estus Flask