简体   繁体   中英

How to import d3 library properly in node.js?

I am working with d3 in order to visualize a force directed graph.

I started my project using a cdn file. But I found one problem, if I use this code:

https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js

..functions like d3.forceSimulation() are not available, at least it throws an error. So I changed the url to this one:

https://d3js.org/d3.v4.min.js

...according to this example Force-Directed Graph

But new problem came out: Uncaught TypeError: Cannot read property 'append' of null , that means, svg .

I tried to install d3 using npm . So I imported d3 :

import * as d3 from 'd3'

However, I cannot get how to append a svg to div

This is my code when error occurs:

graphic/index.js

// import modules
import * as d3 from 'd3'

// export function
const force_graph = (w, h) => {
  let svg = d3.select('#Gforce')
    .append('svg')
    .attr({
      'width': w,
      'height': h,
      'cursor': 'default'
    })

  let circle = svg.append('circle')
    .attr({
      'cx': 325,
      'cy': 270,
      'r': 10,
      'fill': '#7A6464',
      'class': 'dot'
    })
}

module.exports = force_graph

index.js

const graph = require('./graphic')
let w = document.getElementById('Gforce').offsetWidth
let h = document.getElementById('Gforce').offsetHeight
graph(w, h)

How can I import properly d3 library. I tried those options, but I cannot get any results. What am I doing wrong?

EDIT 1

I removed all d3 scripts from html .

I added this in my viz file:

const d3 = require('d3')
const d3SelectionMulti = require('d3-selection-multi')

I also tried:

import * as d3 from 'd3'
import 'd3-selection-multi'

I used .attrs instead .attr according to docs: d3-selection-multi v1.0.1

This is the error it throws after those changes: Uncaught TypeError: d3.select(...).append(...).attrs is not a function

D3.js v4 made breaking api changes. You're in version purgatory. You need to let go of v3 and embrace v4.

functions like d3.forceSimulation() are not available

Because you were trying to use a v4 function that doesn't exist in v3.

But new problem came out: Uncaught TypeError: Cannot read property 'append' of null, that means, svg.

Most likely it's because you're trying to use attr with an object, which v4 doesn't support out of the box.

You need https://github.com/d3/d3-selection-multi

Your import statement is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM