Using d3-tip with npm: “Uncaught TypeError: Cannot

2019-07-14 03:50发布

I've installed d3": "^3.5.17" and "d3-tip": "^0.7.1" using npm (d3-tip documentation). Then in my index.js file I have this code:

var d3 = require('d3');
var d3tip = require('d3-tip')(d3);
console.log('d3 version', d3.version);
var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })

But when I build the index file with browserify and load it in the browser, I see an error from the var tip line:

index.js:247 Uncaught TypeError: Cannot read property 'node' of undefined

This is coming from this function in the d3-tip source code:

function getSVGNode(el) {
  el = el.node()
  if(el.tagName.toLowerCase() === 'svg')
    return el
  return el.ownerSVGElement
}

It looks like this function is expecting a node to be passed to it? But where would this come from?

The build itself does not throw any errors, and I think I'm requiring d3-tip correctly, as per this question. The console statement shows d3 version 3.5.17, as expected.

UPDATE: Here's my package.json file:

{
  "name": "myapp",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "watchify index.js -o main.js --debug --verbose",
    "build": "browserify index.js | uglifyjs > main.min.js"
  },
  "dependencies": {
    "d3": "^3.5.17",
    "d3-tip": "^0.7.1",
    "datatables.net": "^1.10.12",
    "datatables.net-bs": "^1.10.12"
  },
  "devDependencies": {
    "uglifyjs": "^2.4.10",
    "watchify": "^3.2.1"
  }
}

And I installed the files with npm install.

3条回答
贼婆χ
2楼-- · 2019-07-14 04:24

Your line

var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })

must be

var tip = d3.tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })

You can check my implementation @:

Source (Lines: 17, 91, 333-339, 685-692)

Demo

查看更多
Ridiculous、
3楼-- · 2019-07-14 04:43

This was happening because I was trying to use the latest version of d3-tip (which requires v4 of D3) with v3 of D3.

Reverting to older versions of both fixed things:

"d3": "^3.5.17",
"d3-tip": "^0.6.7"
查看更多
叛逆
4楼-- · 2019-07-14 04:47

The problem is your line:

var d3tip = require('d3-tip')(d3);

You should not be calling d3.tip(foo) with the d3 reference itself, but with a d3 selection (which it can then invoke .node() on).

I think this should probably be:

d3.tip = require('d3-tip');
查看更多
登录 后发表回答