Colliot Colliot - 3 months ago 13
Node.js Question

Is ES6 `export class A` equivalent to `module.exports = A`?

When I see the compiled code by Babel, they do not seem to be equivalent.
Actually, the former transforms to

exports.A = A
, which is not equivalent to
module.exports = A
(Maybe it is
module.exports.A = A
?)

So is there an ES6 style
module.export =
? Or the syntax remains still in ES6? Or that syntax is no more recommended in ES6?

Answer

You can use

export default class A {

}

Or

class A {

}

export default A;

Which will export as

exports["default"] = A;
module.exports = exports["default"];

There's an explanation why in the interop section here.

In order to encourage the use of CommonJS and ES6 modules, when exporting a default export with no other exports module.exports will be set in addition to exports["default"].