如何在CommonJS模块中定义类和常量

时间:2018-11-29 13:30:14

标签: node.js commonjs

我已经看到了这个线程,它介绍了如何在CommonJS模块之间共享常量: How do you share constants in NodeJS modules?

但是,如果我希望同一文件也具有应在模块中公开的类,那么我该如何实现?

如果我这样做:

  

module.exports = A类{...}

然后我“使用”了module.exports对象。

有没有办法在同一个文件中同时混合类和常量?

在es6中,我将在每一个之前简单地添加“导出”一词...

3 个答案:

答案 0 :(得分:0)

这很容易弄清楚。现在,假设您有这样的代码。

export class A { }
export const y= 5;

您基本上想要哪个。但这与

相同
class A { }
const x = 5;
exports.A = A;
exports.x = 5;

现在,您也可以弄清楚。打开babel repl并将您的ES6代码粘贴到此处。它将在右窗格中为您提供等效的ES5。

我粘贴了ES6代码并返回

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var A = exports.A = function A() {
  _classCallCheck(this, A);
};

var y = exports.y = 5;

请放心,_classCallCheck只是一种保障,因此您不能只致电A()而不是new A()

希望这会有所帮助。

答案 1 :(得分:0)

如果某个模块可能具有多个导出值,则

module.exports = ...是一个不好的做法。

已经存在一个别名为module.exports的{​​{1}}对象,其目的类似于ES模块中的命名导出:

exports

答案 2 :(得分:0)

让它正常工作。

在X.js文件中,我写道:

constant B = "value";

class A {

}

modules.exports = {
    A: A,
    B: B  
};

在客户端代码中,我使用:

  

const X = require('./ X');

     

让a = new X.A();