Using chart.js with importmaps in rail 7

1.5k Views Asked by At

I am trying to integrate chartjs with importmaps in rails 7 but its not working

I have tried with following procedure

     bin/importmap pin "chart.js@^3.8.0" --download

here is my application.js

    import 'chart.js'

I am getting following error in chrome console and I believe it has something to do with ES modules

Get http://localhost:5000/_/e09df68b.js` net::ERR_ABORTED 404 (Not Found)    chart.js-67657cw24cb.js:1 

Am I missing something or its not possible yet to integrate chart.js with rails 7

3

There are 3 best solutions below

0
On

I was able to solve this by fetching the library from the CDN rather than downloading it. To do this, I first unpinned the downloaded version:

bin/importmap unpin chart.js --download

and then I repinned it without downloading:

bin/importmap pin chart.js

And now it works!

1
On

Manually downloading and pinning the packages from jsdelivr.com worked for me.

Download with curl into vendor/javascript:

curl https://cdn.jsdelivr.net/npm/[email protected]/+esm -o vendor/javascript/chart.js.js
curl https://cdn.jsdelivr.net/npm/@kurkle/[email protected]/+esm -o vendor/javascript/kurklecolor.js

Manually change the import statement in the chart.js.js file to:

import {Color as t} from "kurklecolor"

Manually add pins to your config/importmap.rb:

pin 'chart.js' # https://cdn.jsdelivr.net/npm/[email protected]/+esm
pin 'kurklecolor' # https://cdn.jsdelivr.net/npm/@kurkle/[email protected]/+esm

Now you can just follow the official chart.js documentation. A working example below.

Add to your view:

<canvas id="acquisitions"></canvas>

Add to your Stimulus controller:

import { Controller } from '@hotwired/stimulus';
import { Chart, Colors, BarController, CategoryScale, LinearScale, BarElement, Legend } from 'chart.js'

export default class extends Controller {

  connect() {
    Chart.register(Colors, BarController, BarElement, CategoryScale, LinearScale, Legend);

    const data = [
      { year: 2010, count: 10 },
      { year: 2011, count: 20 },
      { year: 2012, count: 15 },
      { year: 2013, count: 25 },
      { year: 2014, count: 22 },
      { year: 2015, count: 30 },
      { year: 2016, count: 28 },
    ];

    new Chart(
      document.getElementById('acquisitions'),
      {
        type: 'bar',
        data: {
          labels: data.map(row => row.year),
          datasets: [
            {
              label: 'Acquisitions by year',
              data: data.map(row => row.count)
            }
          ]
        }
      }
    );
  }
}
1
On

As of August 2023, the setup for Chartkick (which uses chart.js) with Importmap is described in the Chartkick documentation, which worked for me.

Importmap
In config/importmap.rb, add:

pin "chartkick", to: "chartkick.js"
pin "Chart.bundle", to: "Chart.bundle.js"

And in app/javascript/application.js, add:

import "chartkick"
import "Chart.bundle"