Consuming module with default is incorrect #160

Open
unional opened this Issue Jan 13, 2017 · 2 comments

Projects

None yet

2 participants

@unional
unional commented Jan 13, 2017 edited

rollup-plugin-commonjs: 7.0.0
rollup: 0.41.1

I have a module that does both default and named export (but I think a simple default export only module would demo the same issue) global-store.
It is bundled using rollup.
I then consume it in another module, color-map-rainbow, and use rollup to bundle it too.

When loaded on the browser, the error is global_store_1.default is not a function.
Here is the bundled code: https://github.com/unional/color-map-rainbow/blob/rollup-default-erase/demo/color-map-rainbow.js

The shape of the global-store object is like this:

GlobalStore = {
  default: function() { ...}
  getStore: function() { ... }
}

The issue is these two lines:

...
globalStore = 'default' in globalStore ? globalStore['default'] : globalStore;
...
var global_store_1 = globalStore;
var store = global_store_1.default('color-map-rainbow', {});

https://github.com/unional/color-map-rainbow/blob/rollup-default-erase/demo/color-map-rainbow.js#L5
https://github.com/unional/color-map-rainbow/blob/rollup-default-erase/demo/color-map-rainbow.js#L43

It first replaces globalStore with GlobalStore.default (thus become a function), then accesses global_store_1.default, thus undefined.

@unional
unional commented Jan 13, 2017

You can clone and get that branch to try it out:

git checkout rollup-default-erase
npm install
npm run build

# or 'start' for windows
open demo.html
@cmawhorter

I can't get your repo to work but I think this might be related to rollup/rollup#600. I'm having a similar problem with Joi.

The compiled output is:

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var joi = _interopDefault(require('joi'));

Since Joi module.exports something like module.exports { default: }, commonjs (?) incorrectly wraps it in interopdefault.

In your case, this likely means that instead of global_store_1 being a reference to you object with default and getStore, it becomes a reference to GlobalStore.default itself. Since GlobalStore.default.default is undefined it throws the error.

There might be some reason it's not, but _interopDefault should be rewritten as:

function _interopDefault (ex) { 
  if (typeof ex === 'object') {
    var props = Object.keys(ex);
    if (props.length === 1 && props[0] === 'default') {
      return ex['default'];
    }
    else {
       return ex;
    }
  }
  else {
    return ex;
  }
}

That fixes the problem for me.

Alternatively, you can manually patch the bundled js and unwrap the require call:

var some_dep = _interopDefault(require('some-dep'));

Becomes:

var some_dep = require('some-dep');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment