Laravel Mix and Turbolinks

Viewed 1555

I am having some problems with turbolinks setup. Here is setup: Laravel Mix - with defaults: bootstrap, jquery,..). And just after bootstrap.js file I have included turbolinks. Everything works until page reload - where I always get error. What am I doing wrong?

ERROR:

app.js:1282 Uncaught TypeError: $ is not a function
    at HTMLDocument.<anonymous> (app.js:1282)
    at Object.push../node_modules/turbolinks/dist/turbolinks.js.e.dispatch (vendor.js:105933)
    at r.notifyApplicationAfterPageLoad (vendor.js:105934)
    at r.visitCompleted (vendor.js:105934)
    at r.complete (vendor.js:105933)
    at r.<anonymous> (vendor.js:105933)
    at vendor.js:105933

LINE with ERROR:

document.addEventListener('turbolinks:load',function() {
    new SimpleBar(document.getElementsByClassName("js-simplebar")[0]);
    $(".sidebar-toggle").on("click", function() {
        //...
    });
});

EDIT Here are js includes (compiled - Laravel Mix)

<head>
<script defer src="/js/manifest.js" data-turbolinks-track="true"></script>
<scrip`enter code here`t defer src="/js/vendor.js" data-turbolinks-track="true"></script>
<script defer src="/js/app.js" data-turbolinks-track="true"></script>
</head>

This is my app.js:

require('./bootstrap');
let Turbolinks = require('turbolinks');
Turbolinks.start();

require("./dashboard");
require('./custom/INotifier').run();

require("./theme/bootstrap");
require("./theme/theme");

And bootstrap.js (includes jQuery, bootstrap js, axios,...)

try {

window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');

} catch (e) {}

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
3 Answers

In the error you have shown it is written that Uncaught TypeError: $ is not a function this error mostly comes when jquery is not defined before the script which is calling it.

Add jquery in the head of html, before the turbolinks script by downloading the jquery or via cdn that is

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

move your <script defer src="/js/app.js" data-turbolinks-track="true"></script> above your vendor.js and remove defer from script tags. to load jquery before your code

<head>
    <script src="/js/manifest.js" data-turbolinks-track="true"></script>
    <script src="/js/app.js" data-turbolinks-track="true"></script>
    <scrip src="/js/vendor.js" data-turbolinks-track="true"></script>
</head>

Just try putting JQuery first and then popper js.

try {
window.$ = window.jQuery = require('jquery');
window.Popper = require('popper.js').default;
require('bootstrap');

} catch (e) {}

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

The reason this says so - https://getbootstrap.com/docs/4.0/getting-started/introduction/#js

Related