简体   繁体   English

Node.JS中类的导出语句

[英]Export statement for a class in Node.JS

Node currently enables class construction in Strict mode. Node目前在严格模式下启用类构造。

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? 另一个文件的import语句怎么样?

The same way you would currently "import" or "export" anything else currently in node, using commonJS require and module.exports : 与使用commonJS requiremodule.exports当前“导入”或“导出”当前节点中的任何其他内容的方式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()

This is really an issue with how much Node supports ES6 modules. 这实际上是Node支持ES6模块的问题。 While it currently allows for classes, the import/export features of ES6 are not implemented yet, and relies more on CommonJS require. 虽然它目前允许类,但ES6的导入/导出功能尚未实现,并且更多地依赖于CommonJS要求。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM