简体   繁体   中英

webpack not allowing d3.csv() to load data?

I have configured webpack the way it is suggested here: https://code.likeagirl.io/how-to-set-up-d3-js-with-webpack-and-babel-7bd3f5e20df7

and when I want to load data via d3.csv there's no result.

here's my code:

d3.csv("cities.csv",(error, data) => {dataViz(data)});
function dataViz(incomingData) {
var maxPopulation = d3.max(incomingData, d => parseInt(d.population))
var yScale = d3.scaleLinear().domain([0,maxPopulation]).range([0,460]);
d3.select("svg").attr("style","height: 480px; width: 600px;");

d3.select("svg")
.selectAll("rect")
.data(incomingData)
.enter()
.append("rect")
.attr("width", 50)
.attr("height", d => yScale(parseInt(d.population)))
.attr("x", (d,i) => i * 60)
.attr("y", d => 480 - yScale(parseInt(d.population)))
.style("fill", "#FE9922")
.style("stroke", "#9A8B7A")
.style("stroke-width", "1px")

Nota bene, the cities.csv file is in the same folder as my index.js which contains above code.

Undefined

When I want to load data via d3.csv there's no result.

That means that D3 can't find the file so it returns data as undefined because is searching inside the output directory: dist/cities.csv

You should get some error like this in the browser console:

GET XHR
http://localhost:9000/cities.csv
[HTTP/1.1 404 Not Found 2ms]

Just add cities.csv inside dist to fix the error or check the example below.

Output.publicPath

The publicPath specifies the public URL address of the output files when referenced in a browser. For loaders that embed or tags or reference assets like images, publicPath is used as the href or url() to the file when it's different than their location on disk (as specified by path)

Webpack.config

Add a public path in the config file:

   module.exports = { 
      entry: './src/index.js', 
      output: {
        path: path.resolve('dist'),
        publicPath: "/assets/",
        filename: 'index_bundle.js' 
      }
      ...

Create the dist/assets directory and add the .csv file inside.

Index.js

Add the publicPath + the file name:

d3.csv("/assets/cities.csv",(error, data) => {dataViz(data)});

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