Module.exports and es6 Import Module.exports and es6 Import javascript javascript

Module.exports and es6 Import


export { Tiger } would be equivalent to module.exports.Tiger = Tiger.

Conversely, module.exports = Tiger would be equivalent to export default Tiger.

So when you use module.exports = Tiger and then attempt import { Tiger } from './animals' you're effectively asking for Tiger.Tiger.


If you would like to import:

module.exports = Tiger

you may use following construction:

import * as Tiger from './animals'

Then it will work.

Another option is changing the export as described by @Matt Molnar but it is only possible if you are the author of the imported code.


When module.exports is not set it points to an empty object ({}). When you do module.exports = Tiger, you are telling the runtime the object being exported from that module is the Tiger object (instead of the default {}), which in this case is a function.
Since you want to import that same function, the way to import is using the default import (import tiger from './tiger'). Otherwise, if you want to use named import (import { tiger } from './tiger') you must change the module.exports object or use export keyword instead of module.exports object.

Default import/export:

// tiger.jsmodule.exports = tiger;// orexport default function tiger() { ... }// animal.jsimport tiger from './tiger';

Named import/export:

// tiger.jsmodule.exports = { tiger };// ormodule.exports.tiger = tiger// orexport const tiger = () => { ... }// orexport function tiger() => { ... }// animal.jsimport { tiger } from './tiger';