Search code examples
jquerywebpackwebpack-3webpack-loader

How can I load "jquery-1.4.2" as a module in webpack without modifying its source


I want to include jquery-1.4.2 in parallel with jquery-3.x. I have aliased the paths of both scripts as: jquery1/jquery3

For jquery-3.x the code below works:

require("imports-loader?jQuery=jquery3!app/some.jquery.myplugin");

But If i do the same for jquery1 :

require("imports-loader?jQuery=jquery1!app/some.jquery.mylegacyplugin");

I get at runtime: cannot set property mylegacyplugin of undefined.

The only solution I found till now is to edit jquery-1.4.2. file and add the following at the end of the function:

module.exports=jQuery;

Is there a loader which I can use to avoid editing the source code of jquery?


Solution

  • I have created a repo which demonstrates it

    Install: npm i exports-loader -D. I see that you have installed the imports-loader already.

    And I hope you can modify your plugin to add module.exports.

    myJQueryPlugin.js

    $.fn.greenify = function () {
        debugger;
        this.css("color", "green");
        return this;
    }
    
    module.exports = $;
    

    Add the following rule:

     module: {
                rules: [        
                    {
                        use: "exports-loader?window['jQuery']",
                        test: /jQuery.1.4.2.js$/
                    },  
    

    I have added also a resolve.alias for my jQuery plugin:

     resolve: {
          alias: { // shortcuts             
                "myjqPlugin": path.resolve("src/scripts/plugins/app/myJQueryPlugin.js")),
    

    Then in your index.js

    // you would probably name this `var` differently:
        var my142jQueryIncludingPlugin = require("imports-loader?$=../../libs/jQuery.1.4.2.js!myjqPlugin");
    
        my142jQueryIncludingPlugin("*").greenify();
    

    Result: Everything is green :-)