Home > Software engineering >  Import-Export class in js
Import-Export class in js

Time:04-20

I have a problem when I try to import class in js:

//file 1
export default class myClass {
  constructor(){
    this.name = "name1";
  }
  saysHello(){
   console.log("hello" this.name1);
  }
};
//file 2
import { myClass } from 'file1.js'

//I have tried different alternatives

// alternative 1:
var v1 = new myClass();
v1.saysHello()

//alternative 2:
myClass.saysHello()

//alternative 2:
var v1 = Object.create(myClass);

In all alternatives I have the same error:

Uncaught ReferenceError: can't access lexical declaration 'myClass' before initialization http://127.0.0.1:5500/js/file2.js

In the html :

  <script type="module" src="./js/file1.js"></script>
  <script type="module" src="./js/file2.js"></script>

CodePudding user response:

//file 2
import  myClass from './file-1.js'

//I have tried different alternatives

// alternative 1:
var v1 = new myClass();
v1.saysHello()
  • Related