Charlie
Charlie

Reputation: 197

Laravel Mix (webpack) Inline JS undefined jQuery/vendors

Having a nightmare with this after hours of searching for a solution for something seemingly very common, just going round in circles at the moment.

I've recently changed my Laravel project from using gulp to Laravel Mix, SASS etc all working perfectly but my JS isn't playing ball.

Anything using jQuery * inline * in the blade/php template fails with:

Uncaught ReferenceError: jQuery is not defined

webpack.mix.js (with a selection of modules):

let mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js').extract(
  ['jquery', 'foundation-sites', 'vue', 'toastr', 'jscroll', 'chosen-js', 'what-input']
);

mix.sass('resources/assets/sass/app.scss', 'public/css');

master.blade.php (extract method separates them):

<script type="text/javascript" src="/js/manifest.js"></script>
<script type="text/javascript" src="/js/vendor.js"></script>
<script type="text/javascript" src="/js/app.js"></script>

app.js:

const jQuery = require('jquery');
// window.$ = global.jQuery = $;
// window.jQuery = jQuery;
const toastr = require('toastr');
const chosen = require('chosen-js');
const whatInput = require('what-input');

const Foundation = require('foundation-sites');
const Vue = require('Vue');
const jScroll = require('jscroll');
const mousetrap = require('mousetrap');

I've tried importing instead, straight up requiring, leaving requires out and using the autoload method, nothing appears to work. Some variations will say $ is not defined also, just don't know where to turn.

Could someone possibly guide me in the right direction? Been using Laravel with gulp for years but only with vanilla JS, this webpack has me stumped.

Upvotes: 3

Views: 2079

Answers (1)

Ru Chern Chong
Ru Chern Chong

Reputation: 3756

In your app.js, insert the following at the end of the line

const jQuery = require('jQuery')
// other packages here

window.$ = window.jQuery = jQuery

Upvotes: 2

Related Questions