Petro Gromovo
Petro Gromovo

Reputation: 2171

In laravel 7 app added jquery raise error

In my new laravel 7 app I added jquery with yarn command and in package.json I have :

"dependencies": {
    "bootstrap": "^4.5.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.5.1",
    "turbolinks": "^5.2.0"
}

But when in my resources/js/app.js I set lines :

require('jquery');

require('./bootstrap');

var Turbolinks = require("turbolinks")
Turbolinks.start()

console.log('!! resources/js/app.js jQuery.fn.tooltip.Constructor.VERSION::')
console.log(jQuery.fn.tooltip.Constructor.VERSION)

I got an error :

app.js:30245 Uncaught ReferenceError: jQuery is not defined

Also I tried to use line :

console.log($.fn.tooltip.Constructor.VERSION)

But got similar error ...

I suppose I do not have to set link to jquery.js file in my resources/views/layouts/app.blade.php file ?

How to fix it ?

Upvotes: 2

Views: 120

Answers (1)

Kurt Friars
Kurt Friars

Reputation: 3764

Doing require('jquery'), will only return a new jQuery object using its module.exports. It will not register $ or jQuery in the global namespace. To be able to use $('#button') you need to register $ in the global namespace.

In your bootstrap.js or before you use anything jquery in app.js you can register them in the global scope ( The window object). As you can see from the boiler plate that comes with a default laravel install, you can register jquery like so:

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

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

Upvotes: 2

Related Questions