anthonyshort / deku

Render interfaces using pure functions and virtual DOM
https://github.com/anthonyshort/deku/tree/master/docs
3.42k stars 131 forks source link

babel es6 imports not working #310

Closed queckezz closed 8 years ago

queckezz commented 8 years ago

On the top level you export all the necessary functions:

export default {
  element,
  string,
  dom
}

Sadly, officially this syntax isn't allowed in es6 modules. Exporting like that can't be statically analyzed. It was a bug that existed in babel@5 so that this works but they changed it in babel@6 onwards. See here for some more context, specifically:

If you want CommonJS export behavior, you'll need to use CommonJS directly (or use the plugin in the other answer). This behavior was removed because it caused confusion and lead to invalid ES6 semantics, which some people had relied on e.g. export default { a: 'foo' };

When you look at dist/index.js#L1337-L1341 you can see it generates this:

exports.default = {
  element: _element2.default,
  string: _string2.default,
  dom: _dom2.default
};

Importing the above results in undefined:

import { dom, element as h } from 'deku'
console.log(dom) // -> undefined

What you currently have to do:

import { default as deku } from 'deku'
// or
import deku from 'deku'

console.log(dom.domRenderer) // -> function () { ... }

Solution

To actually solve this you just need to remove default

export {
  dom,
  string,
  element
}

With this, it's now the opposite:

// works as expected
import { dom, element as h } from 'deku'
console.log(dom.domRenderer) // -> function () { ... }

// doesn't work
import deku from 'deku'
console.log(deku) // -> undefined

// so you have to do
import * as deku from 'deku'
console.log(deku) // -> Object {}

This costed me hours before. And that my friends, is why I don't like es6 modules (or im just missing something).

anthonyshort commented 8 years ago

Wow I didn't know about those issues. Not sure why I even put default on that one anyway. There's too many ways to export, I really should just never use default. Ergh. I'll push up a new version with that fix.

anthonyshort commented 8 years ago

Thanks for the long post explaining it too. Super helpful! :)

JoeLanglois commented 8 years ago

Can't wait for the fix :)

anthonyshort commented 8 years ago

Just put out 2.0.0-rc5, I just removed that default export, but I'll check it out in more detail to make sure it's not messing with anything else.