2016-09-09 81 views
5

我使用webpack和TypeScript,看起来d3-tip不能使用webpack。我在鼠标悬停事件上遇到错误 "Uncaught TypeError: Cannot read property 'target' of null"d3-tip不能与webpack一起使用

发生此错误是因为d3-tip模块中的d3.event为null。

我包括模块如下:

const d3: any = require("d3"); 
d3.tip = require("d3-tip"); 

但我想这D3存在和D3 D3的尖端模块中是不同的,这是问题的根源,但我不知道如何解决它。在D3-针尖模块有:

(function (root, factory) { 
    if (typeof define === 'function' && define.amd) { 
     // AMD. Register as an anonymous module with d3 as a dependency. 
     define(['d3'], factory) 
    } else if (typeof module === 'object' && module.exports) { 
     // CommonJS 
     var d3 = require('d3') 
     module.exports = factory(d3) 
    } else { 
     // Browser global. 
     root.d3.tip = factory(root.d3) 
    } 
}(this, function (d3) { 
... 

并将其编译通过的WebPack到

function(module, exports, __webpack_require__) { 

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// d3.tip 
// Copyright (c) 2013 Justin Palmer 
// 
// Tooltips for d3.js SVG visualizations 

(function (root, factory) { 
    if (true) { 
     // AMD. Register as an anonymous module with d3 as a dependency. 
     !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(465)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) 
    } else if (typeof module === 'object' && module.exports) { 
     // CommonJS 
     var d3 = require('d3') 
     module.exports = factory(d3) 
    } else { 
     // Browser global. 
     root.d3.tip = factory(root.d3) 
    } 
}(this, function (d3) { 
... 

,并很明显,AMD正在使用。如果我能得到d3-tip的工厂,我会解决这个问题。

回答

0

我找到了解决方案。正如我认为webpack在需要时会生成每个模块的许多实例。我已经使用single-module-instance-webpack-plugin,它解决了我的问题。

你也只需要在最前一页时间某处初始化D3,它应该像​​文件,其中包括你的供应商库:

// D3 and third-party components 
const d3: any = require("d3"); 
d3.tip = require("d3-tip"); 

对于纯JS初始化很容易。

+0

您是否使用D3版本3或4?我遇到了一个类似的问题,使用带有webpack的d3版本3。 – softweave

2

目标元素的最后一个参数传递给tip.show()

var tip = require("d3-tip"); 
var tooltip = tip().html(d => d.value); 
vis.call(tooltip) 

vis.append("rect") 
    // ... 
    .on("mouseover", function() { 
     tooltip.show.apply(this, [...arguments, this]); 
    }); 

和d3-尖端将它捡起和作为靶使用。从source

54: if (args[args.length - 1] instanceof SVGElement) target = args.pop() 

另一种方式:

.on("mouseover", function(d) { 
    tooltip.show(d, this); 
}); 
相关问题