Reputation: 840
I don't know, how much time I lost looking for solution for this issue. I wanted to use Chart.js in my Laravel project, so I followed instructions described here.
composer require fx3costa/laravelchartjs
(runned)Fx3costa\LaravelChartJs\Providers\ChartjsServiceProvider::class
(added in the right place)npm i chart.js
(used to install chart.js)After that the error appeared: Uncaught ReferenceError: Chart is not defined
. Before and after that I was trying different solutions, but always something was wrong and I think this one should work for me. I probably missed something obvious, but very important.
Have you any ideas?
Should I add something to webpack.mix.js
or bootstrap.js
files after installing with npm
?
EDIT:
If I put <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
in my head
section of blade, everything is working fine, but I'm using laravel-mix
to use a locale file instead of link.
Upvotes: 0
Views: 1511
Reputation: 840
Chart.js
must be loaded before content in order to use it in any Controller
. I was loading my laravel-mix
variables after HTML content (because it includes some big libralies like jQuery etc.), so that's why it couldn't work.
SOLUTION:
At the end of my document I still have my previous script
<script src="{{ asset('js/app.js') }}" ></script>
But now I made a new loadBefore.js
file in resources/js
directory with one line of code:
require('chart.js/dist/chart.js');
If there will be any reason to put there any other javascript code, it will be easy to put it there.
I also added this file to webpack.mix.js
like this:
mix.js('resources/js/loadBefore.js', 'public/js').sourceMaps();
And of course at the end I added this script to the head section in my blade:
<script src="{{ asset('js/loadBefore.js') }}"></script>
Now everything is working and I'm using already existing in my Laravel files chart.js
file. I don't know, someone knows an easier solution, so for now I'm accepting my answer, but I'm still open for suggestions.
Upvotes: 1
Reputation: 139
why you just dont copy the content of
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
in a file at your local, for example: /public/js/chart.js and load it in head
<script src="{{asset('js/chart.js')}}"></script>
Upvotes: 1