d3-tip不适用于webpack

kat*_*zz0 6 javascript d3.js typescript webpack

我使用webpack和TypeScript,似乎d3-tip无法使用webpack.我在鼠标悬停事件上遇到错误 "Uncaught TypeError: Cannot read property 'target' of null".

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

我包括如下模块:

const d3: any = require("d3");
d3.tip = require("d3-tip");
Run Code Online (Sandbox Code Playgroud)

但我想d3-did模块中的d3和d3是不同的,这是问题的根源,但我不知道如何解决它.在d3-tip模块中,我们有:

(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) {
...
Run Code Online (Sandbox Code Playgroud)

它由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) {
...
Run Code Online (Sandbox Code Playgroud)

而AMD显然正在使用它.如果我能得到d3-tip的工厂,我会解决这个问题.

eag*_*gor 5

将目标元素作为最后一个参数传递给 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]);
    });
Run Code Online (Sandbox Code Playgroud)

d3-tip会将其拾取并用作目标。来自来源

if (args[args.length - 1] instanceof SVGElement) target = args.pop()
Run Code Online (Sandbox Code Playgroud)

其它的办法:

.on("mouseover", function(d) {
    tooltip.show(d, this);
});
Run Code Online (Sandbox Code Playgroud)


kat*_*zz0 2

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

您还只需要在第一次初始化 d3 的某个地方,它应该是像vendor.ts包含供应商库的文件一样:

// D3 and third-party components
const d3: any = require("d3");
d3.tip = require("d3-tip");
Run Code Online (Sandbox Code Playgroud)

对于纯 JS 初始化会很容易。