Adding apexcharts to sage 10 theme

Hi,
I am trying sage 10 for the first time and all going well, however; Trying to add apexcharts.js is causing issue, I have confirmed the node module is installed and package.json lists apexcharts as a dependency.
This is my app.js, alpinejs is working as expected but apexcharts results in
Uncaught ReferenceError: ApexCharts is not defined

import { domReady } from '@roots/sage/client'
import Alpine from 'alpinejs'
import ApexCharts from 'apexcharts'

/**
 * app.main
 */
async function main(err) {
  if (err) {
    // handle hmr errors
    console.error(err);
  }

  // application code
  document.addEventListener('DOMContentLoaded', function () {
    var replacers = document.querySelectorAll('[data-replace]');
    for (var i = 0; i < replacers.length; i++) {
      let replaceClasses = JSON.parse(
        replacers[i].dataset.replace.replace(/'/g, '"')
      );
      Object.keys(replaceClasses).forEach(function (key) {
        replacers[i].classList.remove(key);
        replacers[i].classList.add(replaceClasses[key]);
      });
    }
  });

}
/**
 * Initialize
 *
 * @see https://webpack.js.org/api/hot-module-replacement
 */
domReady(main)
import.meta.webpackHot?.accept(main)
window.Alpine = Alpine
window.ApexCharts = ApexCharts
Alpine.start()

Any guidance appreciated

Haven’t worked with ApexCharts before but it seems that you should be using ApexCharts as layed out in their docs:

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("#chart"), options);

chart.render();

Remove the window.ApexCharts = ApexCharts-part.

Does that work? Just my 2 cents…

1 Like

Hi evance, thanks for the quick reply. I should have mentioned that I have the code you mentioned in my html, in fact it is the line beginning var chart = new ApexCharts which is generating the unreferenced error. I removed the window.ApexCharts=ApexCharts line but no change

Quickly gave the setup a try and haven’t had any issues…

Steps:

  • yarn add apexcharts
  • import ApexCharts from 'apexcharts' on top of app.js
  • add window.ApexCharts = ApexCharts to make it globally available
  • call ApexCharts from the browser console – works

Maybe start anew?

Did you do a yarn build after adding apexcharts?

1 Like

Thanks for that, will try reset up over the weekend