admin管理员组

文章数量:1335386

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?

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?

Share Improve this question edited May 17, 2022 at 12:03 Ashton Six asked Nov 13, 2015 at 0:49 Ashton SixAshton Six 5135 silver badges21 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

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;

本文标签: javascriptes2015 moduleshow to name exports dynamicallyStack Overflow