How to use both default export and normal exports in RequireJS?

lib.js

exports.value = 'Some value'

module.exports = {
  libraryName: '@CoolLibrary'
}

main.js

const { value } = require('./lib')
console.log('Value is '.concat(value))

When I write a code like above, see the output as Value is undefined. However, I have exported the value as Some value in the library.

Seems like I’m missing something.

What is the right way to export using both module.exports and export.[value] in Node.js?

Answer

exports is an alias for module.exports, so when you do

module.exports = {
  libraryName: '@CoolLibrary'
}

you completely replace the object that you just assigned value to, making value unavailable.

This is one good reason not to replace the exports object; instead, just add to it:

exports.value = 'Some value';
exports.libraryName = '@CoolLibrary';

or if you like:

Object.assign(exports, {
    value: 'Some value',
    libraryName: '@CoolLibrary'
});

Leave a Reply

Your email address will not be published. Required fields are marked *