问题描述
我有一个文件 d3.custom.build.js
像这样(简化):
I've got a file d3.custom.build.js
like this (simplified):
import { range } from 'd3-array';
import { select, selectAll, event } from 'd3-selection';
import { transition } from 'd3-transition';
export default {
range,
select,
selectAll,
event,
transition
};
还有一个像这样的 rollup.config.js
:
import nodeResolve from 'rollup-plugin-node-resolve';
export default {
entry: './js/vendor/d3-custom-build.js',
dest: './js/vendor/d3-custom-built.js',
format: 'iife',
globals: {
d3: 'd3'
},
moduleId: 'd3',
moduleName: 'd3',
plugins: [nodeResolve({ jsnext: true })]
};
我想导出到一个名为d3"的普通旧浏览器全局.我正在从一个简单的 npm 脚本中调用 rollup.好消息是几乎所有内容都在输出文件中工作,除了一件事:浏览器中的 d3.event
始终为空.不,这不是页面上的事件被劫持的问题.当我将标准的完整 d3 4.0 库交换到脚本标记中时,一切正常.这绝对是一个构建问题.
I want to export to a plain old browser global named 'd3'. I'm calling rollup from a simple npm script. The good news is that almost everything works in the output file, except for one thing: d3.event
in browser is always null. No, it's not an issue with events being hijacked on the page. When I swap in the standard full d3 4.0 library into the script tag everything works fine. It's definitely a build issue.
d3 文档 警告捆绑event
很棘手:
如果您使用 Babel、Webpack 或其他 ES6-to-ES5 打包器,请注意d3.event 的值在事件期间发生变化!一个进口d3.event 必须是实时绑定,因此您可能需要配置bundler 从 D3 的 ES6 模块导入,而不是从生成的UMD 捆绑;并非所有打包程序都遵守 jsnext:main.还要小心与 window.event 全局冲突.
似乎设置 nodeResolve({ jsnext: true })
是不够的.如何在捆绑包中获得实时绑定?非常感谢任何指导.
It appears that setting nodeResolve({ jsnext: true })
isn't sufficing. How do I get a live binding in the bundle? Any guidance very appreciated.
推荐答案
您要导出使用 ES2015 速记对象字面量语法定义的对象作为默认导出.这是与您所写内容等效的长格式:
You’re exporting an object, defined using ES2015 shorthand object literal syntax, as the default export. Here is the long form equivalent of what you’ve written:
export default {
range: range,
select: select,
selectAll: selectAll,
event: event,
transition: transition
}
您的对象因此在加载时捕获 event
的值,该值为空;它不是实时绑定,不会反映当前事件.
Your object thus captures the value of event
on load, which is null; it is not a live binding, and won’t reflect the current event.
一种解决方法是使用 getter 定义 event
属性:
One fix would be to define the event
property using a getter:
export default {
range,
select,
selectAll,
get event() { return event; },
transition
}
最好使用命名导出而不是默认导出,然后 Rollup 将自动生成实时绑定:
Better would be to use named exports instead of a default export, and then Rollup will generate a live binding automatically:
export {
range,
select,
selectAll,
event,
transition
}
这不仅更短,而且现在您不依赖于支持 ES2015 速记对象字面量语法的浏览器.
This is not only shorter, but now you don’t depend on the browser supporting the ES2015 shorthand object literal syntax.
这篇关于使用汇总将 d3.event 导入自定义构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!