Bald Bantha Bald Bantha - 3 months ago 9
Javascript Question

Include es6 class from external file in Node.js

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.

mmm mmm
Answer

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
Comments