How to install chartjs on laravel 6 via npm

1.7k views Asked by At

I would like to ask how install and integrate [email protected] with my laravel application.

I use cdn links right now but later it wont be an option for me later.

Used cdn links:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

Method I tried:

  1. Installing chartjs
npm i [email protected]
  1. Add this line in webpack.mix.js:
mix.copy('node_modules/chart.js/dist/chart.js', 'public/chart.js/chart.js');
  1. Then run this from command line:
npm run dev
  1. In the blade you want the chart on:
<script src="{{ asset('chart.js/chart.js') }}"></script>
1

There are 1 answers

0
BritishWerewolf On BEST ANSWER

Install the package:

npm install chart.js

Make a file called something like /resources/js/mychart.js:

import Chart from 'chart.js/auto';

let ctx = document.getElementById('myChart').getContext('2d');
let myChart = new Chart(ctx, {
    // ...
});

In your /resources/js/app.js, add the following, at the top:

import './mychart.js';

Now run your build, to compile your JavaScript into one file.

npm run dev

Laravel Mix, will already have a line for compiling the app.js file.

Now whenever you reference /public/js/app.js, your chart will be included there too.

<script src="{{ mix('/js/app.js') }}"></script>

If you'd like a separate file, then change your webpack.mix.js file to this:

mix.js('/resources/js/chart.js', 'public/js');

And remember to remove it from the imports in the /resources/js/app.js file.