Search code examples
javascriptecmascript-6es6-modulesumd

`Object.defineProperty(exports, '__esModule', { value: true })` vs `exports.__esModule = true`


I figured that this:

Object.defineProperty(exports, '__esModule', { value: true })

Should give the same result as this:

exports.__esModule = true

But all UMD bundle generators I've seen have used the first option. Is there a reason?


Solution

  • Object.defineProperty() has different defaults than just assigning the property normally. Specifically, the following attributes all default to false if you don't specify them:

    configurable
    enumerable
    writable
    

    So, Object.defineProperty(exports, '__esModule', { value: true }) will have the same value, but will not be configurable, enumerable or writable whereas exports.__esModule = true will have all those attributes default to true.

    You can read about this level of detail on Object.definePropert() here on MDN.

    But all UMD bundle generators I've seen have used the first option. Is there a reason?

    Presumably, the designers of those tools want that property configured so it can't be changed (writable) or deleted (configurable) or enumerated.