Spixi
Spixi

Reputation: 119

Uncaught ReferenceError: $ is not defined - Laravel 9, Vite

I'm trying to import jQuery in my Laravel 9 project, which I installed with npm i jquery

I'm getting Uncaught ReferenceError: $ is not defined

in my app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">

    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
</head>

in my another view, which extends app.blade.php

<script>
  $(function(){
      alert('jquery ok');
  })
</script>

in resources/js/app.js

I tried all sorts of things

import $ from 'jquery';
import $ from 'jquery';

window.jQuery = $;
window.$ = $;
import inject from '@rollup/plugin-inject';

export default {
    plugins: [
        // Add it first
        inject({
            $: 'jquery',
        }),
        // Other plugins...
    ],
    // The rest of your configuration...
};
try {
    window.$ = window.jQuery = require('jquery');
} catch (e) {}

Nothing works. How can I fix this?

npm - 8.11.0 node - 16.16.0 laravel/framework - 9.32.0 vite - 3.14

Upvotes: 3

Views: 6791

Answers (5)

Sadee
Sadee

Reputation: 3180

I followed this article to install & setup jQuery in Laravel 9:

Install jQuery

npm install jquery --save-dev

Import jQuery through bootstrap This needs to be just after lodash import

import $ from 'jquery';
window.$ = $;

In the blade file

<script type="module">
    $('body').html('<h1>Hello World!</h1>');
</script>

App build:

npm run build

Upvotes: 1

JohnnyAce
JohnnyAce

Reputation: 3749

For me the problem was on how the libraries are imported on the bootstrap.js. I changed the file:

import _ from 'lodash';
// Since I'm using jquery from admin-lte 🤷 
import $ from 'admin-lte/plugins/jquery/jquery';
import * as Popper from 'popper.js';
// Since I'm using jquery from admin-lte 🤷 
import 'admin-lte/plugins/bootstrap/js/bootstrap'
window._ = _;
window.Popper = Popper.defaults;
window.$ = window.jQuery = $;

Now you can use

<script type="module">
    $(function () {
        console.log('Jquery loaded');    
    });
</script>

Upvotes: 0

Nick
Nick

Reputation: 171

If you'd like to use javascript dynamic imports because some pages may not require jQuery.

Build tools/bundlers like ViteJs, WebPack, Laravel Mix and others support this.

Inside your app.js

async function main() {
  const { default: jQuery } = await import('jquery')
  window.jquery = window.jQuery = window.$ = jQuery;

  // code that uses jQuery
  console.log('jQuery v', $().jquery);
}

main();

You could put the import in side an if statement

async function main() {

  if (document.querySelector('.useJquery')) {
    const { default: jQuery } = await import('jquery')
    window.jquery = window.jQuery = window.$ = jQuery;

    // code that uses jQuery
    console.log('jQuery v', $().jquery);
  }
}

In any page that requires jQuery you could add class="useJquery".

Then only pages with the useJquery class will download JQuery.

Upvotes: 0

Spixi
Spixi

Reputation: 119

The answer to my question was to be found here ReferenceError: $ is not defined, Jquery Import with vite

<script type="module"> //type="module" is the important part
    $(function () {
        alert('jquery ok');
    })
</script>

Upvotes: 8

Sergio
Sergio

Reputation: 668

Where are you importing your JQuery files? (JS and CSS)

You need something like this on your head section: (obviously you have to specify your actual path to those files)

<link href="./jquery-files/jquery-ui.css" rel="stylesheet">
<script src="./jquery-files/external/jquery/jquery.js"></script>
<script src="./jquery-files/jquery-ui.min.js"></script>

Then you just need to use a script tag like this:

<script type="text/javascript">

    $().ready(function () {
        //add all JQuery related code here!!
        alert('jquery ok'); //this will show an alert when the page is loaded
    });

</script>

Upvotes: 0

Related Questions