Forum Discussion

jfk's avatar
jfk
New Contributor
8 years ago

how to import a javascript class

hi,

I would like to import a javascript class to another file but unfortunately I couldn't successfully do that :)

I tried something like this:

 

 

// fileA
class A{
    constructor(x){
      this.x = x
}
    getX(){
      return this.x
 }
}
module.exports.class = A;

//fileB
var ss = require("fileA");

var tt =  new ss.A("2")

but this doesn't work. Couldn't someone help me out ? :)

  •  

    Your syntax is a bit off.  When you do modules.exports.class = A; you're basically saying that the class "A" is exported to other modules as "class".  Try the following and see if it works (worked for me).

     

    // fileA
    class A{
        constructor(x){
          this.x = x
    }
        getX(){
          return this.x
     }
    }
    module.exports.A = A;
    
    //fileB
    var ss = require("fileA");
    
    var tt =  new ss.A("2")

     

  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor

     

    Your syntax is a bit off.  When you do modules.exports.class = A; you're basically saying that the class "A" is exported to other modules as "class".  Try the following and see if it works (worked for me).

     

    // fileA
    class A{
        constructor(x){
          this.x = x
    }
        getX(){
          return this.x
     }
    }
    module.exports.A = A;
    
    //fileB
    var ss = require("fileA");
    
    var tt =  new ss.A("2")