Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 703
Colliot Avatar asked May 06 '15 15:05

Colliot


People also ask

Is module exports the same as export?

exports and module. exports are the same unless you reassign exports within your module.

What is export default in ES6?

Export Default is used to export only one value from a file which can be a class, function, or object. The default export can be imported with any name.

What are the two types of module exports in JavaScript?

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.

Can you export classes in JavaScript?

Use named exports to export a class in JavaScript, e.g. export class Employee {} . The exported class can be imported by using a named import as import {Employee} from './another-file. js' . You can use as many named exports as necessary in a file.


2 Answers

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"].

like image 136
Ben Fortune Avatar answered Sep 20 '22 20:09

Ben Fortune


You can use the following in Node v6:

"use strict" 

class ClassName {
 // class code
}

module.exports = ClassName

Save the above file as ClassName.js

To import it in another file Test.js:

"use strict"
var ClassName= require('./ClassName.js');
var obj = new ClassName( Vars . . . );

For more Info:

Here's an article on exporting classes from modules in Node v6

like image 25
Rishabh.IO Avatar answered Sep 21 '22 20:09

Rishabh.IO