简体   繁体   English

您可以从单个Nodejs模块导出多个类吗?

[英]Can you export multiple classes from a single Nodejs Module?

Currently, I have 4 Child Classes each in their own file. 目前,我在自己的文件中有4个子类。 I'm requiring them all in the same file. 我要求他们都在同一个文件中。 I am wondering if I can contain all 4 of those classes in a single module. 我想知道我是否可以在一个模块中包含所有这四个类。 Currently, I'm importing them like this 目前,我正在这样导入它们

var Jack = require('./Jack.js');
var JackInstance = new Jack();
var Jones = require('./Jones.js');
var JonesInstance = new Jones();

I'd like to import them like this 我想像这样导入它们

var People = require('./People.js');
var JackInstance = new People.Jack();

Or even 甚至

var Jack = require('./People.js').Jack;
var JackInstance = new Jack();

My classes are defined like so 我的课程定义如此

class Jack{
    //Memeber variables, functions, etc
}

module.exports = Jack;

You can export multiple classes like this: 您可以导出多个这样的类:

eg People.js 例如People.js

class Jack{
   //Member variables, functions, etc
}

class John{
   //Member variables, functions, etc
}

module.exports = {
  Jack : Jack,
  John : John
}

And access these classes as you have correctly mentioned: 并且正如您正确提到的那样访问这些类:

var People = require('./People.js');
var JackInstance = new People.Jack();
var JohnInstance = new People.John();

You can also do this in a shorter form, using destructuring assignments (which are supported natively starting from Node.js v6.0.0 ): 您也可以使用解构分配 (本机从Node.js v6.0.0开始支持)以较短的形式执行此操作:

// people.js
class Jack {
  // ...
}

class John {
  // ...
}

module.exports = { Jack, John }

Importing: 输入:

// index.js
const { Jack, John } = require('./people.js');

Or even like this if you want aliased require assignments: 或者甚至像这样,如果你想要别名需要分配:

// index.js
const {
  Jack: personJack, John: personJohn,
} = require('./people.js');

In the latter case personJack and personJohn will reference your classes. 在后一种情况下, personJackpersonJohn将引用您的课程。

A word of warning: 一句警告:

Destructuring could be dangerous in sense that it's prone to producing unexpected errors. 从某种意义上讲,解构可能会产生意外错误。 It's relatively easy to forget curly brackets on export or to accidentally include them on require . export忘记大括号或者在require上意外地包含它们相对容易。

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

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