Home > Software design >  why am i not able to import the class to another js file
why am i not able to import the class to another js file

Time:09-09


class hello{
    var1;
    var2;
    constructor(var1, var2){
        this.var1 = var1;
        this.var2 = var2;
    }

    getVar(){
        console.log(this.var1);
        console.log(this.var2);
    }
}
class h1 extends hello{
    var3 ;
    constructor(var1, var2,var3)
    {
        super(var1,var2);
        this.var3 = var3;
    }

    getAll(){
        console.log(this.var1);
        console.log(this.var2);
        console.log(this.var3);
    }
}

export {h1};
export {hello};

This is module that i want to import from another file

this is the code of another file

import {h1,hello} from './temp'

let a = new h1("likith","ramu","asha");
a.getAll();
let b = new hello("raju","rahil");
b.getVar();

And this is the error that i'm getting for this code Please solve this problem

** (node:14232) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use node --trace-warnings ... to show where the warning was created) c:\Full stack dev Code\react.js\temp1.js:1 import {h1,hello} from './temp' ^^^^^^

SyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1033:15) at Module._compile (node:internal/modules/cjs/loader:1069:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) at node:internal/main/run_main_module:17:47

[Done] exited with code=1 in 0.125 seconds

**

CodePudding user response:

Since you are trying to import a module it will be better if you try exporting your classes as a module as well, like this, module.exports = { h1, hello }; and then you can import it in your other file like this, const { h1, hello } = require("./temp");. Hope this solves your problem

CodePudding user response:

Try the first letter in the capital—class Hello and H1.

  • Related