Export statement for a class in Node.JS

Node currently includes building a class in strict mode.

If I have the following class:

"use strict"

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

   func(){/*ETC */}
 }

What is the appropriate export operator for exporting it to another module. What about an import statement from another file?

+4
source share
2 answers

Similarly, you are currently “importing” or “exporting” anything else currently to node using commonJS requireand 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()
+2
source

, Node ES6. , / ES6 CommonJS.

:

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

   func(){/*ETC */}
 }

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

:

//in app.js

var myClass = require('./MyClass');
var mc = new myClass(foo);
+1

Source: https://habr.com/ru/post/1616460/


All Articles