import and use d3 in frontend

Viewed 19

I know this might be a really silly question. But it would mean a lot to me to finally really grasp it!

So I simply want to include and use D3 (but could be any other npm-package) in the browser.

So I create a directory and an index.html. I start a new npm-project with npm init -y, I install the depencies npm install d3. I create a file called main.js that looks like this:

// main.js
import * as d3 from "d3";
console.log(d3.scaleLinear());

where the index.html

// index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./main.js" defer></script>
</head>

<body>
    this is the body
</body>

</html>

looks like this and the package.json like this:

{
  "name": "HowDoesNpmWork",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "d3": "^7.6.1"
  }

Yet I do get the error in the browser after running npx serve

Uncaught SyntaxError: import declarations may only appear at top level of a module main.js:1

I am not really getting my head around it. I am installing D3 and I'm saying it's a module in the package.json. What I am conceptually misunderstanding here? Can't I simply use any npm-package in the frontend?

And why does it work when I import D3 like this in the index.html ?

import * as d3 from "https://cdn.skypack.dev/d3@7";

Isn't it doing the same as loading it from node_modules ?

I'd

1 Answers

You have to add that your code is a module

<script src="./main.js" type="module"></script>

This still depends on D3 allowing direct import like this. Not all packages you install with npm install will work directly in the browser like this.

The other solution is to use a module bundler like parcelJS. This is the more traditional way to use npm in the front-end.

Related