Issue using Alpine.data() in Livewire component on npm run build
On a livewire component I want to show some chartjs chart. To do this I prefer to import the chart.js and use it within Alpine.data() only on the pages where this component is used. To illustrate:
import Chart from 'chart.js/auto'
Alpine.data('chart', () => ({
data: null, // wired up through x-modelable
chart: null,
init() {
// data is bound to wire:model and not directly available on init
// so we need to wait till it is available
this.$watch('data', value => {
if (value) {
this.initChart()
}
})
},
initChart() {
this.chart = new Chart(el, {
//...
});
}
// other functions for manipulating the chart
}));
Unfortunately I can't get it to work. I can't import chart.js within an inline script due to the import. So I thought of extracting it to a js file and bundling it within the livewire chart component blade file, using:
@assets
@vite([
Modules/Admin/resources/assets/mock-ups/chartjs/chart.js',
])
@endassets
When running vite through npm run dev this works. when using npm run build (for staging and production), however, this breaks and I get the js error: "Alpine Expression Error: chart is not defined". The only difference that I can find is the way the chart.js is included on the page.
Using npm run dev it injects it like:
<script type="module" src="http://127.0.0.1:5173/Modules/Admin/resources/assets/mock-ups/chartjs/chart.js" data-navigate-track="reload"></script>
while using npm run build it injects:
<link rel="modulepreload" href="{***}/build/assets/chart-5cb8d83e.js">
Could this indeed be the issue, and how could I solve this?
Wrapping Alpine.data() in document.addEventListener('alpine:init', () => { /**/ }); doesn't fix it unfortunately.
Please or to participate in this conversation.