Include es6 class from external file in Node.js

Let's say I have a class.js file:

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

And I wanted to use the myClass class in another file. How can i do this?
I tried:
var myClass = require('./class.js');
But that did not work. I looked through module.exports but did not find an example that works for es6 classes.

+5
source share
2 answers

Or do

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

and import using

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

or use the new syntax (you may need to update your code first)

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

and import using

 import {myClass} from "./class.js"; 
+13
source
 export default class myClass { constructor(arg){ console.log(arg); } } 

Another file:

 import myClass from './myFile'; 
+1
source

All Articles