4

Node currently enables class construction in Strict mode.

If I have the following class:

"use strict"

 class MyClass {
   constructor(foo) {
     this.foo = foo
   }

   func(){/*ETC */}
 }

What is the corresponding export statement for it to be exportable to another module. What about the import statement from another file?

TheM00s3
  • 3,677
  • 4
  • 31
  • 65

2 Answers2

2

The same way you would currently "import" or "export" anything else currently in node, using commonJS require and module.exports:

Foo.js

class Foo {}
module.exports = Foo
// or if you want to edit additional objects:
// module.exports.Foo = Foo
// module.exports.theNumberThree = 3

Bar.js

var Foo = require("./Foo")
var foo = new Foo()
lyjackal
  • 3,984
  • 1
  • 12
  • 25
1

This is really an issue with how much Node supports ES6 modules. While it currently allows for classes, the import/export features of ES6 are not implemented yet, and relies more on CommonJS require.

To export use the following:

//MyClass.js
class MyClass {
   constructor(foo) {
     this.foo = foo
   }

   func(){/*ETC */}
 }

 module.exports = function(foo){
   return new MyObject(foo);
 }

To Import:

//in app.js

var myClass = require('./MyClass');
var mc = new myClass(foo);
TheM00s3
  • 3,677
  • 4
  • 31
  • 65