Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
Ashton Six Avatar asked Oct 29 '25 05:10

Ashton Six


1 Answers

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;
like image 186
Felix Kling Avatar answered Oct 30 '25 22:10

Felix Kling