Webpack using bootstrap - jquery is not defined

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

import $ from 'jquery'; require("./node_modules/bootstrap/dist/css/bootstrap.min.css") require("./node_modules/bootstrap/js/dropdown.js") import React from 'react'; import ReactDOM from 'react-dom'; var _ = require('lodash'); 

Please refer above my setting . Some reason I've got error saying "Uncaught ReferenceError: jQuery is not defined() from dropdown.js

I also included the following lines at webpack.config.js

   plugins: [     new webpack.NoErrorsPlugin({         $: "jquery",         jQuery: "jquery"     }) ] 

But, No luck - Still having jQuery undefined error. Any idea ? Can someone help this issue please?

Many thanks

回答1:

please use webpack ProviderPlugin, use global is not a good idea.

// webpack.config.js module.exports = {     ...     plugins: [         new webpack.ProvidePlugin({            $: "jquery",            jQuery: "jquery"        })     ] }; 


回答2:

global.jQuery did not work for me. But I found an interesting read here: http://reactkungfu.com/2015/10/integrating-jquery-chosen-with-webpack-using-imports-loader/

The basic idea is to use webpacks 'imports-loader'. Notice, though, that it's not installed by default, so first thing install (npm install --save imports-loader). And in webpack.config add to your loaders the following:

{ test: /bootstrap.+\.(jsx|js)$/, loader: 'imports?jQuery=jquery,$=jquery,this=>window' } 

After that just import jquery and bootstrap, or some other plugins extending on 'jQuery', as usually.

regards



回答3:

This will work!

global.jQuery = require('jquery'); 

instead of

import $ from 'jquery'; 


回答4:

In order for this code to work you must RESTART Node after the change:

// webpack.config.js module.exports = {     ...     plugins: [         new webpack.ProvidePlugin({            $: "jquery",            jQuery: "jquery"        })     ] }; 


回答5:

As mentioned by @Ro don't forget to restart the node server, the changes to the webpack will otherwise not be taken into account.

I confirm that once these lines added and the server restarted the error vanishes.

With Bootstrap 4 an updated version of the webpack.config.js will look actually like this because of its dependency with Tether:

plugins: [ // ...plugins... new webpack.ProvidePlugin({   $: "jquery",   jQuery: 'jquery',   "window.jQuery": 'jquery',   tether: 'tether',   Tether: 'tether',   'window.Tether': 'tether', }), ] 


回答6:

this will work

plugins: [       new webpack.ProvidePlugin({            $: "jquery",             jQuery: "jquery"      }) ]  

It worked for me hope it helps



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