Search code examples
jquerywebpackwebpack-2

Loading jQuery plugins with webpack 2


After spending most of the day googling and trying - i did not get it to work and at this point i'm not sure what's missing.
I already have jQuery working (and verified it works) in webpack.common.js:

new ProvidePlugin({
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery'
    }) 

For example i have a "MetisMenu" plugin, where should i configure it?

I tried various combinations of require/include in my app.module.ts.
Like (including assigning them to a constant/var but import/require always give this error):

import 'metismenu';
jQuery(...).metisMenu is not a function

import { metisMenu } from 'metismenu';
Cannot assign to read only property 'exports' of object '#<Object>'

require ('metismenu');
Cannot assign to read only property 'exports' of object '#<Object>'

import * as jQuery from 'jquery';
import "metismenu";
Cannot assign to read only property 'exports' of object '#<Object>'

Solution

  • Looks like webpack.ProvidePlugin makes somehow declared globals immutable in Webpack 2.

    I was unable to modify jQuery from a module and then use the modified jQuery on the other (hear by that, adding a jQuery plugin that add its own $.fn.).

    I suggest you to create a single define that contains the necessary jQuery plugins "requires", it worked for me, e.g.:

    ((root, factory) => {
        // AMD. Register as an anonymous module.
        define([
            'modernizr'
        ], factory);
    })(this, (Modernizr) => {
    
        // Do the requires here instead of doing it on the main file
    
        // Fix broken $.animate so Slick can work with
        require('./animatePolyfill');
    
        // Inject carousel there
        require('slick-carousel');
    
        class Core extends PluginBase {
        ...