Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform an export that is compatible with ES5 and ES6?

I'm writing a "class" in node

// mymodule/index.js

function MyClass() {}
MyClass.prototype.method1 = function() {..}

usually I do

module.exports = MyClass

but I want my class available for both syntax

var MyClass = require('mymodule')

and

import {MyClass} from 'mymodule'

Which is the correct way to do it?

like image 572
rkmax Avatar asked May 14 '15 15:05

rkmax


People also ask

How do I know if I have ES6 or ES5?

Object manipulation is less time-consuming in ES6. 7. In ES5, both function and return keywords are used to define a function. An arrow function is a new feature introduced in ES6 by which we don't require the function keyword to define the function.

What is ES5 and ES6?

ES6. Definition. ES5 is the fifth edition of the ECMAScript (a trademarked scripting language specification defined by ECMA International) ES6 is the sixth edition of the ECMAScript (a trademarked scripting language specification defined by ECMA International).

Does ES6 Import Export?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


2 Answers

As far as writing an export that is compatible for both ES5 and ES6, Babel already takes care of that for you. (As communicated in the comments to your question. I'm only clarifying for those who got lost in the dialog.)

module.exports = MyClass

will work with both var MyClass = require('mymodule') and import MyClass from 'mymodule

However, to be clear, the actual syntax you asked about:

import {MyClass} from 'mymodule'

means something different from

import MyClass from 'mymodule'

For the latter, you would have to export it as: module.exports.MyClass = MyClass, and for ES5 modules it would have to required as var MyClass = require('mymodule').MyClass

like image 138
Lioness Avatar answered Oct 18 '22 00:10

Lioness


Both ways are correct, but try to import in es6 like this without the brackets:

import MyClass from 'mymodule'

Otherwise you would have to export your function like this:

module.exports.MyClass = MyClass

and than import it like this:

import { MyClass } from 'mymodule'
like image 31
Arwed Mett Avatar answered Oct 18 '22 00:10

Arwed Mett