Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  10] [ 6]  / answers: 1 / hits: 39331  / 8 Years ago, wed, august 17, 2016, 12:00:00

Say I have a file class.js:



class myClass {
constructor(arg){
console.log(arg);
}
}


And I wanted to use the myClass class in another file. How would I go about this?

I've tried:

var myClass = require('./class.js');

But it didn't work.

I've looked at module.exports but haven't found an example that works for es6 classes.


More From » node.js

 Answers
207

Either do



module.exports = class MyClass {
constructor(arg){
console.log(arg);
}
};


and import with



var a = require(./class.js);
new a(fooBar);





or use the newish syntax (may require you to babelify your code first)



export class MyClass {
constructor(arg){
console.log(arg);
}
};


and import with



import {myClass} from ./class.js;

[#61005] Monday, August 15, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;