Home > Net >  Issue with using browserify to bundle D3 library
Issue with using browserify to bundle D3 library

Time:12-26

I want to learn D3 library. So I've installed it via npm. After a while I encountered an issue while applying transition on a svg object (see my original question here: transision() causes Uncaught TypeError with D3 version 7.2.1). I was adviced to bundle up the library to solve the issue.

I've been struggling with bundling D3 library using browserify. I've done these steps:

  1. Used require function in a module file and give it as an argument the library name ("d3")
  2. Referenced the module file and bundle.js file in a html document
  3. In a directory containing the module file ran command: browserify module.js > bundle.js

After I ran the command I got this:

....\node_modules\d3\src\index.js:1 export * from "d3-array"; ^ ParseError: 'import' and 'export' may appear only with 'sourceType: module'

I'm completely clueless what I'm doing wrong.

CodePudding user response:

Before I give you a solution I want to give you the context to the actual problem.

Browserify allows you to combine multiple javascript files into one file. This really just saves you from needing to include multiple <script> tags in your html.

From my perspective it is a cleaner, simpler version of webpack/rollup but, less versatile.

D3 appears to be written in a version of javascript that supports import/export statements and uses Rollup to convert it to vanilla javascript that the browser (and browserify) can understand.

The Answer

Import the final version of d3 that is transpiled already.

const d3 = require('d3/dist/d3');


// do something with d3 here
const targetElem = d3.select('#target');

targetElem.text('HELLO WORLD');
  • Related