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

rkmax picture rkmax · May 14, 2015 · Viewed 28.4k times · Source

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?

Answer

Lioness picture Lioness · Apr 15, 2017

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