如何有选择地导入ES2015模块功能,但具有命名空间? [英] How to import ES2015 modules functions selectively, but with namespacing?
问题描述
我开始使用ES2015模块编写的Rollup和D3版本4.我已经使用传统的D3名称空间"d3"编写了一些代码.现在,我想使用汇总创建一个自定义捆绑包.我想使用摇树,因为我可能只使用了d3中大约一半的功能,而且我想让东西尽可能的轻.
I'm getting started with Rollup and D3 version 4, which is written in ES2015 modules. I've written a some code using the traditional D3 namespace "d3". Now I want to create a custom bundle using Rollup. I want to using tree-shaking, because I'm probably only using about half the functions in d3, and I want to keep things as light as possible.
很明显,我可以有选择地导入函数,例如:
I'm clear that I can import functions selectively, e.g.:
import {scaleLinear} from "d3-scale";
import {
event,
select,
selectAll
} from "d3-selection";
这将变得非常冗长,因为d3的一半具有很多功能.我可以忍受这一点.更大的问题是,它还需要完全重写我的所有函数标识符而没有名称空间.我对此不太在乎,因为我更喜欢命名空间库代码.
That is going to get very verbose very fast, because half of d3 is a lot of functions. I can live with that. The bigger problem is that it also would require completely rewriting all my function identifiers without a namespace. I don't much care for that, because I prefer to namespace library code.
我知道我可以导入所有模块:
I understand that I can import all of the module:
import * as d3 from "d3";
保留了d3对象名称空间,这对我的代码组织很有用.但是,然后汇总无法将未使用的功能从捆绑包中摇出来.
which preserves the d3 object namespace, which is good for my code organization. But then Rollup can't tree-shake the unused functions out of the bundle.
我梦dream以求的东西是这样的:
What I'm dreaming of is something like:
import {
event,
select,
selectAll
} as d3 from "d3-selection";
,但是规范中似乎不存在这种功能/语法.如何既可以有选择地定位模块的各个部分,又可以在导入期间保留命名空间?
but that sort of feature/syntax doesn't seem to exist in the spec. How can I both selectively target individual parts of a module, and preserve namespacing during an import?
推荐答案
为此您需要重新导出模块:
You need a re-exporting module for that:
export {
event,
select,
selectAll
} from "d3-selection";
import * as d3 from './d3';
这篇关于如何有选择地导入ES2015模块功能,但具有命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!