2016-09-09 85 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); 
}); 
相關問題