我已经按照这里建议的方式配置了 webpack:https://code.likeagirl.io/how-to-set-up-d3-js-with-webpack-and-babel-7bd3f5e20df7
当我想通过 d3.csv 加载数据时,没有结果。
这是我的代码:
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")
注意,cities.csv 文件与包含上述代码的 index.js 位于同一文件夹中。
最佳答案
未定义
When I want to load data via d3.csv there's no result.
这意味着 D3 找不到该文件,因此它返回未定义的数据
因为在输出目录中搜索:dist/cities.csv
您应该会在浏览器控制台中收到类似这样的错误:
GET XHR
http://localhost:9000/cities.csv
[HTTP/1.1 404 Not Found 2ms]
只需在 dist
中添加 cities.csv
即可修复错误或检查下面的示例。
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
在配置文件中添加公共(public)路径:
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('dist'),
publicPath: "/assets/",
filename: 'index_bundle.js'
}
...
创建dist/assets
目录并在里面添加.csv
文件。
索引.js
添加publicPath
+ 文件名:
d3.csv("/assets/cities.csv",(error, data) => {dataViz(data)});
关于javascript - webpack 不允许 d3.csv() 加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49331523/