Anji
Anji

Reputation: 111

Uncaught ReferenceError: jQuery is not defined at eval

I have imported the jQuery in main.js file but still it throws this error

Uncaught ReferenceError: jQuery is not defined at eval (navbar.js)

I am unable to fix this. I tried every possible way to import in main.js

I used the jQuery CDN link in the public/index.html file, this error is gone but the navbar script which is present inside the navbar.js file does not work at all.

Installed jquery using npm npm install jquery --save

navbar.js

(function ($) {
    'use strict';

    if ($.fn.kanglaNav) {
        $('#bigNavBar').kanglaNav();
    }

    $(".kangla-navbar-toggler").on("click", function () {
        $(".top-header").toggleClass("z-index-reduce");
    });

})(jQuery);

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './assets/css/style.css'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import './assets/css/kangla-nav.min.css'
import './assets/css/animate.css'
import '../node_modules/magnific-popup/dist/magnific-popup.css'
import './assets/js/popper.min.js'
import '../node_modules/bootstrap/dist/js/bootstrap.min.js'
import './assets/js/kangla-nav.min.js'
import '../node_modules/magnific-popup/dist/jquery.magnific-popup.min.js'
import './assets/js/navbar.js'

const { $, jQuery } = require('jquery')
window.$ = $
window.jQuery = jQuery

new Vue({
    router,
    store,
    render: (h) => h(App)
}).$mount('#app')

Upvotes: 1

Views: 1870

Answers (1)

Estus Flask
Estus Flask

Reputation: 222379

jQuery global variable is undefined at the time when it's accessed because import './assets/js/navbar.js' line is evaluated before window.jQuery = jQuery. jquery doesn't contain $, etc exports, global variables will be undefined any way.

Moving jQuery assignment above import would be incorrect because import statements are hoisted by specs.

A way to fix this is to move window.jQuery = jQuery to jquery.js and import it before modules that depend on it.

A more correct way is to not rely on globals in modular environment and import them in modules that depend on them:

import jQuery from 'jquery';

Upvotes: 1

Related Questions