首页 > 解决方案 > ES 模块:将命名导出作为模块导入?

问题描述

funcs.js

export function hello() {
  echo 'foo'
}

export function foo() {
  echo 'bar'
}

index.js

import * as Funcs from './funcs.js' // import module, does tree-shaking work?
import { hello } from './funcs.js' // optimise imports, potentially clashes with other imports
import { hello } as Funcs from './funcs.js' // what should make sense, but isn't supported syntax

// this should be straight forward... 
Funcs.hello()

// vs having some random function on top level scope
hello()

// and this shouldn't work if I didn't import it
Funcs.foo()

那是我的问题。如果我使用表格 1 和表格 2,它对摇树有什么影响吗?表格 2 更适合表达,但表格 1 是我可以将所有内容放入模块/命名空间的唯一方法。表格 3 是我的建议,但也许我不知道有人还没有反对为什么不应该支持它。

我不知道去哪里建议这个,甚至构建一个 babel 插件来做到这一点。

编辑:对于上下文,我正在使用一些不公开默认导出的较新库(rxjs),并依赖开发人员加载他们需要的所有功能。所以我无法控制这些出口。

编辑:建议的解决方法是简单地创建一个全局导入文件,该文件导入所有全局所需的导入,并将其全部导出为模块,这就是我现在正在做的事情。

编辑:找到 es-discuss。将去那里而不是希望转发讨论。

https://esdiscuss.org/topic/syntax-to-pick-named-exports-from-a-module

https://esdiscuss.org/topic/proposal-importing-selected-chucks-of-a-module-into-an-object

编辑:在这里找到最有启发性的讨论。

https://esdiscuss.org/topic/import-foo-bar-as-obj-from-module

标签: javascripttypescriptecmascript-6es6-modules

解决方案


原来我不是唯一一个有这种想法的人。该线程更详细地介绍了与此语法相关的一些潜在问题......我不一定同意,但事实就是如此。

https://esdiscuss.org/topic/import-foo-bar-as-obj-from-module


推荐阅读