Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Uncaught ReferenceError: jQuery is not defined' with create-react-app

Am building a React App using create-react-app so the app is server ready.

When importing a bootstrap javascript plugin such as 'affix.js', I get the error 'Uncaught ReferenceError: jQuery is not defined', and the page no longer loads.

Am importing all the modules through the index.js file since with the create-react-app it dosent seem to load the 'src' and 'link' imports from the index.html file.

Am importing the bootstrap plugin like so: import 'bootstrap/js/affix.js'

Have tried importing jquery in the following ways, at the top of the index.js file but none is working:

  1. import jquery from 'jquery'
  2. import jquery from 'jquery', window.$ = window.jQuery = jquery;
  3. import jQuery from 'jquery'
  4. import $ from 'jquery'
  5. import 'jquery/dist/jquery.js';
  6. require('./node_modules/jquery/dist/jquery.js')

Any ideas?

like image 959
Sami El Maameri Avatar asked Dec 18 '22 10:12

Sami El Maameri


2 Answers

Create React App maintainer here.

import $ from 'jquery';

and then using

$.something()

should work fine if you are using jQuery 2.x or higher.

If it doesn't please file an issue.


In your examples, the problem might be that you wrote import jquery from 'jquery' but used jQuery as variable name. You should have written import jQuery from 'jquery' (or any other name as long as you use it consistently). Variable names are case sensitive in JavaScript.

like image 133
Dan Abramov Avatar answered Jan 14 '23 13:01

Dan Abramov


In case someone land here. I had resolved similar issue for 'create-react-app' by using this:

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

and for importing other packages that needs jQuery you should import those packages after this, in affix.js case,

require 'bootstrap/js/affix.js';
like image 40
Upasana Avatar answered Jan 14 '23 13:01

Upasana