I am using Webpack 4 for the build process of my React app.
My app uses jQuery and I want to import
jQuery plugin but get the following error:
Failed to compile.
./jquery-plugin.js
Line 3: 'jQuery' is not defined no-undef
I've tried the methods described here and here but neither helped me.
// app.js
import $ from 'jquery';
// import './jquery-plugin.js';
window.$ = window.jQuery = $;
require('./jquery-plugin.js');
// jquery-plugin.js
(function($) {
// Plugin code
})(jQuery);
If I understand this approach works correctly in the previous Webpack versions.
If I add import jQuery from 'jquery'
to jquery-plugin.js
for test it works fine but I cannot do this since it is 3rd party plugin.
Does anyone have ideas how to make jQuery visible globally in Webpack 4?
UPD:
I use react-app-rewired for override Webpack config. Here is my config:
// config-overrides.js
const webpack = require('webpack');
module.exports = function override(config, env) {
//do stuff with the webpack config...
config.module.rules.push({
// Exposes jQuery for use outside Webpack build
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
});
config.plugins.push(
new webpack.ProvidePlugin({
//provide jquery in all the ways 3rd party plugins might look for it (note that window.$/window.jQuery will not actually set it on the window, which is cool)
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}));
config.resolve = {
alias: {
'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
},
};
return config;
};