0

I have seen this thread on how to share constants across CommonJS modules: How do you share constants in NodeJS modules?

However, if I want the same file to also have a class which should be exposed in the module, then how do I achieve that?

If I do:

module.exports = class A { ... }

Then I "used" the module.exports object.

Is there a way to mix both class AND constants in the same file?

In es6, I would simple add the term "export" before each one...

Nir
  • 221
  • 3
  • 12

3 Answers3

0

This is fairly easy to figure out. Now, let's say you have a code like this.

export class A { }
export const y= 5;

Which you basically want. But this is same as

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

Now, you can figure it out also. open up babel repl and paste your ES6 code there. It will give you the ES5 equivalent in the right pane.

I pasted that ES6 code and got back

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

Don't worry about _classCallCheck it is just a safeguard so that you cannot just call A() instead of new A()

Zoe
  • 27,060
  • 21
  • 118
  • 148
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
0

module.exports = ... is a bad practice if there's a chance that a module can have more than one exported value.

There's already existing module.exports object that is aliased as exports, it's purpose is similar to named exports in ES modules:

exports.A = class A { ... };

exports.b = 'constant';
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

Got it to work.

In file X.js I write:

constant B = "value";

class A {

}

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

In the client code I use:

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

let a = new X.A();

Nir
  • 221
  • 3
  • 12