React Error : __WEBPACK_IMPORTED_MODULE_4_jquery___default(…)(…).modal is not a function

一世执手 提交于 2020-02-03 13:15:28

问题


I'm working on a react project with Bootstrap 4. Bootstrap has been imported through CDN.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

what I wanted is to show/hide a modal if a condition is satisfied. I have already imported jquery also using

npm install jquery --save

in component

import $ from 'jquery'; <-to import jquery

$('#addSupModal').modal('show'); <- to show modal

but during the execution time when the above line gets executed, it shows an error like

Unhandled Rejection (TypeError): __WEBPACK_IMPORTED_MODULE_4_jquery___default(...)(...).modal is not a function

I read about this error and it says maybe because jquery is imported twice with CDN and npm. I don't know for sure what the reason. But I also tried importing jquery from only one method but it doesn't work. Any suggestions?


回答1:


Your import import $ from 'jquery' creates a local variable named $ inside your module, which then gets used by $('#addSupModal').modal('show') (instead of the global $ you wanted).

The quickest fix would be to explicitly use the jQuery $ from the global context (which has been extended with your $.modal() because you referenced that in your script tag when you did <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>):

window.$('#addSupModal').modal('show')

It would be better though to not include the jQuery and plugins with script tags at all, because that way you are creating implicit dependencies (which is, your module cannot run without those script tags). Instead, import Bootstrap as well:

import $ from 'jquery'; <-to import jquery
import 'bootstrap';

$('#addSupModal').modal('show'); // <- to show modal


来源:https://stackoverflow.com/questions/52464915/react-error-webpack-imported-module-4-jquery-default-modal-is-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!