cancel
Showing results for 
Search instead for 
Did you mean: 

how to import a javascript class

SOLVED
New Contributor

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 ? 🙂

1 ACCEPTED SOLUTION

Accepted Solutions
Community Hero

Re: how to import a javascript class

 

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")

 


Robert Martin
[Hall of Fame]
Please consider giving a Kudo if I write good stuff
----

Why automate?  I do automated testing because there's only so much a human being can do and remain healthy.  Sleep is a requirement.  So, while people sleep, automation that I create does what I've described above in order to make sure that nothing gets past the final defense of the testing group.
I love good food, good books, good friends, and good fun.

Mysterious Gremlin Master
Vegas Thrill Rider
Extensions available

View solution in original post

2 REPLIES 2
Community Hero

Re: how to import a javascript class

 

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")

 


Robert Martin
[Hall of Fame]
Please consider giving a Kudo if I write good stuff
----

Why automate?  I do automated testing because there's only so much a human being can do and remain healthy.  Sleep is a requirement.  So, while people sleep, automation that I create does what I've described above in order to make sure that nothing gets past the final defense of the testing group.
I love good food, good books, good friends, and good fun.

Mysterious Gremlin Master
Vegas Thrill Rider
Extensions available

View solution in original post

New Contributor

Re: how to import a javascript class

thank you

New Here?
Join us and watch the welcome video:
Announcements
Top Kudoed Authors