Skip to content
Advertisement

es2015 modules – how to name exports dynamically

I would like to create a module, h, which exports one function for every HTML element. Here’s how it might be used:

import {div, p} from 'h'

const myDiv = div(p('some text'))

Here’s how that module is defined:

const h = {}
for (let tagName of ['div', 'p', /* ... */]) {
  h[tagName] = (...children) => {
    // ...
  }
}

export const div = h.div
export const p = h.p
/* ... */

I don’t like that every export has to be listed explictly. How do I make these dynamic?

Advertisement

Answer

how to name exports dynamically

You can’t. import and export statements are specifically designed this way because they have to be statically analyzable, i.e. the import and export names have to be known before the code is executed.

If you need something dynamic then do what you are already doing: Export a “map” (or object). People can still use destructuring to just get what they want:

const {div} = h;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement