es2015 模块 - 如何动态命名导出 [英] es2015 modules - how to name exports dynamically

查看:19
本文介绍了es2015 模块 - 如何动态命名导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中 react-hyperscript 被柯里化并暴露了一组默认函数,所以 h('div', props, children) 变成了 div(道具,儿童).

In this example react-hyperscript is curried and exposes a set of default functions, so h('div', props, children) becomes div(props, children).

import hyperscript from 'react-hyperscript';
import {curry} from 'lodash';

const isString = v => typeof v === 'string' && v.length > 0;
const isSelector = v => isString(v) && (v[0] === '.' || v[0] === '#');

const h = curry(
  (tagName, first, ...rest) =>
    isString(tagName) && isSelector(first) ?
      hyperscript(tagName + first, ...rest) :
      hyperscript(tagName, first, ...rest)
);

const TAG_NAMES = [
  'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', // ...
];

TAG_NAMES.forEach(tagName =>
  Object.defineProperty(h, tagName, {
    value: h(tagName),
    writable: false,
  })
);

export default h;

在另一个模块中:

import h, {div} from 'lib/h';

console.log(
  h,        // h
  div,      // undefined <- problem!
  h('div'), // div
  h.div     // div
)

这可以通过将其附加到示例(来自 lodash 的 zip)来解决:

This can be resolved by appending this to the example (zip from lodash):

const {
  a, abbr, address, area, // ...
} = zip(
  TAG_NAMES,
  TAG_NAMES.map(h)
)

export {
  a, abbr, address, area, // ...
}

但是这个解决方案不是很优雅,有人知道更好的选择吗?

But this solution isn't very elegant, does anybody know a better alternative?

推荐答案

如何动态命名导出

how to name exports dynamically

你不能.importexport 语句是专门以这种方式设计的,因为它们必须是静态可分析的,即导入和导出名称必须之前知道代码被执行.

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;

这篇关于es2015 模块 - 如何动态命名导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆