简体   繁体   English

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

[英]'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.我正在使用create-react-app构建一个 React 应用程序,以便该应用程序准备好服务器。

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.导入引导程序 javascript 插件(例如“affix.js”)时,出现错误“未捕获的 ReferenceError:未定义 jQuery”,并且页面不再加载。

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.我通过 index.js 文件导入所有模块,因为使用 create-react-app 它似乎从 index.html 文件加载“src”和“link”导入。

Am importing the bootstrap plugin like so: import 'bootstrap/js/affix.js'我正在像这样导入引导插件: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:尝试通过以下方式导入 jquery,在 index.js 文件的顶部,但没有一个工作:

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

Any ideas?有任何想法吗?

Create React App maintainer here.在此处创建 React App 维护者。

import $ from 'jquery';

and then using然后使用

$.something()

should work fine if you are using jQuery 2.x or higher .如果您使用 jQuery 2.x 或更高版本,应该可以正常工作。

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.在您的示例中,问题可能是您编写了import jquery from 'jquery'但使用jQuery作为变量名。 You should have written import jQuery from 'jquery' (or any other name as long as you use it consistently).您应该编写import jQuery from 'jquery' (或任何其他名称,只要您一直使用它)。 Variable names are case sensitive in JavaScript.变量名在 JavaScript 中区分大小写。

In case someone land here.万一有人降落在这里。 I had resolved similar issue for 'create-react-app' by using this:我已经通过使用这个解决了“create-react-app”的类似问题:

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,为了导入需要 jQuery 的其他包,您应该在此之后导入这些包,在 afix.js 的情况下,

require 'bootstrap/js/affix.js';

您可以复制反应“公共”文件夹中的 jquery.js 文件并将其导入您的 index.html 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM