davidcb's avatar

Problem with webpack and modules availability

Hi, I have a problem importing npm modules and then using it on my code. Some of them return, for example, "ReferenceError: Chart is not defined" even if that module is on my compiled .js file.

In /resources/assets/js/app.js I'm requiring ./bootstrap.js, as Laravel's default config.

My bootstrap.js file looks like:

...
try {
    window.$ = window.jQuery = require('jquery');

    require('jquery-ui');
    require('jquery-datepicker');
    require('bootstrap');
    require('sweetalert');
    require('dropzone');
    require('cropper');
    require('chart.js');
} catch (e) {}
...

On my layout blade file, I have the following:

...
<script src="/js/app.js"></script>
@yield('scripts')
...

And finally, on my view:

...
@section('scripts')
@parent

<script>
    $(function() {
        var ctx = document.getElementById("campaignChart").getContext('2d');
        var myChart = new Chart(ctx, {
...
@endsection

Even if I move the code from my view to the /resources/assets/js/app.js below the calling to bootstrap.js it still doesn't work.

Can anyone point me on the right direction?

Thanks in advance

0 likes
2 replies
wilburpowery's avatar
Level 23

Try assigning Chart to the window object. Like:

window.Chart = require('chart.js');

You must keep in mind that you are using a build system. You need to initialize all those libraries manually.

If you were simply using a cdn, you can call the Chart object itself.

davidcb's avatar

Thank you very much, it worked like a charm.

I wasn't understanding well how it works.

Please or to participate in this conversation.