using ApexChart for rails7 raising error Uncaught ReferenceError: ApexCharts is not defined

3.1k Views Asked by At

I'm new one in rails and trying to add Apexchart js to my project in rails7.

So i did

document.addEventListener('turbo:load', function(){

  var options = {
    chart: {
      type: 'line'
    },
    series: [{
      name: 'sales',
      data: [30,40,35,50,49,60,70,91,125]
    }],
    xaxis: {
      categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999]
    }
  }

  var chart = new ApexCharts(document.querySelector('.user-apex-chart'), options);

  if (chart) {
    chart.render();
  }


})

before I run npm install apexcharts --save

I have Esbuild and turbo on

and add to application.js this:

import ApexCharts from 'apexcharts'

in package.json it has apex

"dependencies": {
    "@hotwired/turbo-rails": "^7.1.1",
    "@popperjs/core": "^2.11.5",
    "apexcharts": "^3.35.3",
    "bootstrap": "^5.1.3",
    "bootstrap-icons": "^1.8.1",
    "esbuild": "^0.14.38",
    "sass": "^1.51.0",
    "tom-select": "^2.0.0"
  },

no erorrs when I started the server.. but seems it doesn't see Apex.

What I did wrong?

the test code following below is working:

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
1

There are 1 best solutions below

1
On

This is likely caused because your application.js script tag has defer="defer" and the library by default renders script tags that expect ApexCharts to exist.

Explanation of defer

The library supports passing defer: true to the options argument and then it will wrap create chart code inside an event listener.

 <%= line_chart series, {defer: true} %>

I don't know if the event listener will work with turbo yet though.