I\'m using Webpack in my application, in which I create two entry points - bundle.js for all my JavaScript files/codes, and vendors.js for all libraries like jQuery and Reac
In your webpack.config.js file add below:
var webpack = require("webpack");
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
Install jQuery using npm:
$ npm i jquery --save
In app.js file add below lines:
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
This worked for me. :)
I tried some of the supplied answers but none of them seemed to work. Then I tried this:
new webpack.ProvidePlugin({
'window.jQuery' : 'jquery',
'window.$' : 'jquery',
'jQuery' : 'jquery',
'$' : 'jquery'
});
Seems to work no matter which version I'm using
This works for me on the webpack.config.js
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
in another javascript or into HTML add:
global.jQuery = require('jquery');
Add this to your plugins array in webpack.config.js
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
'window.$': 'jquery',
})
then require jquery normally
require('jquery');
If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)
window.$ = jQuery;
I got things working nicely while exposing $
and jQuery
as global variables with Webpack 3.8.1 and the following.
Install jQuery as a project dependency. You can omit @3.2.1
to install the latest version or specify another version.
npm install --save jquery@3.2.1
Install expose-loader
as a development dependency if not installed already.
npm install expose-loader --save-dev
Configure Webpack to load and expose jQuery for us.
// webpack.config.js
const webpack = require('webpack')
module.exports = {
entry: [
// entry bits
],
output: {
// output bits
},
module: {
rules: [
// any other rules
{
// Exposes jQuery for use outside Webpack build
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
]
},
plugins: [
// Provides jQuery for other JS bundled with Webpack
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
}
Edit: Sometimes you want to use webpack simply as a module bundler for a simple web project - to keep your own code organized. The following solution is for those who just want an external library to work as expected inside their modules - without using a lot of time diving into webpack setups. (Edited after -1)
Quick and simple (es6) solution if you’re still struggling or want to avoid externals config / additional webpack plugin config:
<script src="cdn/jquery.js"></script>
<script src="cdn/underscore.js"></script>
<script src="etc.js"></script>
<script src="bundle.js"></script>
inside a module:
const { jQuery: $, Underscore: _, etc } = window;