d3 is not defined - ReferenceError

会有一股神秘感。 提交于 2019-11-28 20:27:47

There may be security restrictions that prevent your browser from downloading the D3 script. What you can do is to download the scripts, place them in the same folder as your files and change the referenced paths in your source.

Had the same issue, though I initially thought it is because of security restrictions of browser, that wasn't the case. It worked when I added the charset to the script tag as shown below:

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

The same is shown in the d3 docs, though it doesn't mention this issue specifically: http://d3js.org/

Yes, having it locally works too.

<script src="d3.min.js"></script>

Here is the full example:

<!doctype html>
<html>
<head>
    <title>D3 tutorial</title>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <!--<script src="d3.min.js"></script>-->
</head> 
<body>
    <script>
        var canvas = d3.select("body")
                        .append("svg")
                        .attr("width", 500)
                        .attr("height", 500);
        var circle = canvas.append("circle")
                        .attr("cx",250)
                        .attr("cy", 250)
                        .attr("r", 50)
                        .attr("fill", "red");
    </script>
</body> 
</html>

You may also need to add:

<meta charset="utf-8">

or

<meta content="utf-8" http-equiv="encoding">

to your head section

in case browser does not prevent it from downloading and still getting the error, d3.js should be placed before jquery.

I had to do a grunt build to get get rid of this error. (Using Yeoman and Ember.js.)

Replace <meta charset="ISO-8859-1"> with <meta charset="UTF-8">

UPDATE: there is now a d3-webpack-loader package which makes it easy to load d3 in webpack. I am not the creator of the package, I've only used it to see if it works. Here's a quick example.

// Install the loader
npm install --save d3-webpack-loader

// Install the d3 microservices you need
npm install --save d3-color
npm install --save d3-selection

In our entry.js file we'll require d3 using the d3-webpack-loader with:

const d3 = require('d3!');

and can then use some of the d3 methods with:

d3.selectAll("p").style("color", d3.color("red").darker());

If you are using Visual Studio you can go to Tools -> Options -> Text Editor -> JavaScript -> IntelliSense and check the box "Download remote references". That did the trick for me.

And for JavaScript noobs like me - problem could be that you don't import it correctly. Try reading import docs and things like:

import * as d3 from 'd3-transition'

I just moved my reference to the package as the first import in my head tag:

<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
...
...
</head>

Seemed to work for me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!