ProEvilz
ProEvilz

Reputation: 5455

Why do I get undefined JS with Laravel?

I'm using Laravel and in my bootstrap.js file I have

window.ProgressBar = require('progressbar.js');

and then I require the bootstrap.js file into app.js

require('./bootstrap');

And I use webpack.mix.js to compile it

mix.js('resources/assets/js/app.js', 'public/js')

If I attempt to access progressbar.js inside of app.js it works perfectly.

However, If I attempt to use it outside of app.js in script tag that comes after app.js on my pages, ProgressBar is undefined.

How can I access ProgressBar outside of my app.js but keep it imported via app.js ?

Example on index.blade.php

<script src="app.js" defer></script>
<script>
  const progress = new ProgressBar; //undefined...
</script>

Upvotes: 0

Views: 566

Answers (2)

ProEvilz
ProEvilz

Reputation: 5455

I had defer on the script tag and for some reason that stopped it from working.

Solution:

<script src="app.js" defer></script>

change to

<script src="app.js"></script>

Upvotes: 1

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

I think, that Webpack hides ProgressBar from you, even if you have ProgressBar assigned to the window. Because you know, Webpack thinks that the bundle has all the code of your app. Solution? Not to bundle it! Instead use minified version of ProgressBar and just load it like in good old times. It is perfectly OK, few nanoseconds better or worse, not noticeable.

Upvotes: 0

Related Questions