Home > Blockchain >  "Uncaught ReferenceError" from d3 with importmaps on Ruby On Rails
"Uncaught ReferenceError" from d3 with importmaps on Ruby On Rails

Time:05-14

I have little experience of building charts with d3 but not general web dev. I want to build a charting example site and opted to use Ruby on Rails. I'm having trouble getting d3 library to be working. I am a complete newbie to Rails. This is my steps

  1. Used ./bin/importmap pin d3 --download to get a local version of d3. I can see a number of d3 files under the vendor/javascript folder. This has also created a number of records in importmap.rb e.g. pin "d3" # @7.4.4

  2. In the application.js file I have: import "d3"

  3. I have test js file called "charts" and referencing this with import "./charts" in application.js

  4. Test file contains

window.onload = function() {var svg = d3.select("#rankChart1")
                .append("svg")
                .attr("width", 1000)
                .attr("height", 1000);
                }

  1. This fails with "Uncaught ReferenceError: d3 is not defined. I can see a number of d3 files under the Assets folder in the browser so not sure why it is not working.

CodePudding user response:

With importmaps d3 is not exported globally, that's why you're getting an error.

Pin d3:

$ bin/importmap pin d3

A whole lot of pins gets added. You can use all of them:

import * as d3 from "d3";      // NOTE: every d3 module is loaded

Or just pick and choose for faster load time:

import {zip} from "d3-array";  // NOTE: from `name` has to match the pin `name`

or make a custom d3 object:

const d3 = await Promise.all([
  import("d3-array"),
  import("d3-axis"),
]).then(d3 => Object.assign({}, ...d3));

If you want the old behavior where d3 is just global. Add this pin manually to config/importmap.rb file:

pin 'd3', to: 'https://cdn.jsdelivr.net/npm/d3@7'

and then just import it:

// app/javascript/application.js

import "d3";
import "./chart"; // import after d3

console.log(d3); // d3 is already global and can be used anywhere.
// app/javascript/chart.js

console.log(d3.select); // d3 is loaded correctly

For more options: https://github.com/d3/d3#installing

  • Related