Importing D3 in a JavaScript module via script tag

Viewed 1439

When importing D3 in a JavaScript module via a script tag I get an Uncaught TypeError: Cannot read property 'd3' of undefined error.

Having read that all main browsers now support JavaScript modules, I am trying to import my D3 code via a <script type="module" src="network.js"></script> tag as described here:

https://developers.google.com/web/fundamentals/primers/modules

However, when I import D3 I receive the error:

d3.js:5 Uncaught TypeError: Cannot read property 'd3' of undefined
    at d3.js:5
    at d3.js:6

If I have an index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
</head>
<body>
<script type="module" src="network.js"></script>
</body>
</html>

With D3 v5.7.0 in the same directory and network.js simply containing:

import * as d3 from "./d3.js";

or just

import "./d3.js";

the above error is received.

I would expect the same behaviour found with CommonJS or AMD:

https://github.com/d3/d3-interpolate/issues/45#issuecomment-329590699

0 Answers
Related