score:0

Accepted answer

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 Query

More Query from same tag