Webpack and jQuery plugins

Sebastian Kurfürst14.03.2017

In a project, I recently wanted to migrate jQuery and jQuery plugins to a Webpack based build setup. Turns out this is more complicated than anticipated!

Here's the working configuration for me, with explanations following below:

webpack.config.js

const webpack = require('webpack');
const path = require('path');

module.exports = {
entry: {
app: [
'./Private/index.js'
]
},
module: {
rules: [
{
test: /(jquery.magnific-popup.min.js|slick.min.js|jquery.unveil2.js|readmore.min.js)/,
loader: "imports-loader?define=>undefined,exports=>undefined"
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
],
},
resolve: {
alias: {
'jquery$': path.resolve(__dirname, 'Resources/Private/Js/vendor/jquery.min.js'),
}
}
};

index.js

// the following two lines load jQuery AND expose it on the window object. (window.jQuery, window.$)
require('expose-loader?jQuery!jquery');
window.$ = window.jQuery;
require('./your-script-files.js')

Explanation

  • index.js - we first use the expose-loader to expose jQuery to the global state before loading other scripts
  • because many jQuery plugins use some kind of "AMD/CommonJS/plain" detection logic, we need to explicitely disable this; because otherwise they will not find the global jQuery.
    • The best way to disable we found was using the imports-loader; actually un-setting the "define" and "exports" statements.

Dein Besuch auf unserer Website produziert laut der Messung auf websitecarbon.com nur 0,28 g CO₂.