1

I'm using v7.6.1 of D3.js. I am also using Astro. I wrote this code:

var margin = {top: 20, right: 30, bottom: 40, left: 90}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom;

d3.select("div")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.top)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json("./data.json", function (data) {
    console.log(data);
});

But whenever I try to run it in a developer environment, it throws this error:

file:///D:/thatheatedcoin/node_modules/d3-selection/src/select.js:5
      ? new Selection([[document.querySelector(selector)]], [document.documentElement])
                        ^

ReferenceError: document is not defined
    at Proxy.default (file:///D:/thatheatedcoin/node_modules/d3-selection/src/select.js:5:25)
    at eval (/src/components/viz.astro:17:25)
    at renderToIterable (/node_modules/astro/dist/runtime/server/index.js:463:27)
    at renderAstroComponentInline (/node_modules/astro/dist/runtime/server/index.js:132:28)
    at renderAstroComponentInline.next (<anonymous>)
    at _render (/node_modules/astro/dist/runtime/server/index.js:41:5)
    at async AstroComponent.[Symbol.asyncIterator] (/node_modules/astro/dist/runtime/server/index.js:60:7)
    at async renderAstroComponent (/node_modules/astro/dist/runtime/server/index.js:563:20)
    at async _render (/node_modules/astro/dist/runtime/server/index.js:39:5)
    at async _render (/node_modules/astro/dist/runtime/server/index.js:34:5)
error Command failed with exit code 1.

Could this be related to Astro? If not, what is causing it? Thank you!

mikwee
  • 133
  • 2
  • 14

1 Answers1

0

D3 client side

Astro is a server side generator framework so code in its frontmatter --- runs on server and only code in the body inside <script> tag executes on the client, there window and document are accessible

see also similar question, and not this answer with simple <script> tag as more attributes are not required How to use document and window element in astro JS?

---
//Astro Front matter => runs on server only
---
<script>
    //here use document and use d3
</script>

D3 server side

This is also possible but then everything happen without using neither window nor document and generation provides an svg, but for interactivity you'd need to add client js. see How to use D3js on server side to generate SVG directly?

wassfila
  • 1,173
  • 8
  • 18