Search code examples
javascriptwebpackyarnpkg

Dependencies with webpack


So I'm using webpack encore within a symfony project, and I have this github repo with a jQuery plugin, and I would like to import this plugin to use it in my code, but I don't get how to do that; even though I'm sure it's a very classic use case... This dependency should be resolved with yarn or webpack, or both ? I googled of course but I didn't find anything expliciting it. I don't really master webpack, so I'm really looking for a "step by step"-like explaination. I own the repository that has the plugin, it has a bower.json file, but no other package manager file (so no package.json file for instance) but I totally can add some support if needed (I guess it will be needed).

The plugin code is something like that :

jQuery.fn.extend({
    pluginFunction: function(options) {
        return $(this).each(function() {
            // code
        });
    }
});

So to rephrase : I own a repository with a jQuery module. With the javascript code of my other project, I want to be able to use it (for instance $('#selector').pluginFunction(); ). Thank you


Solution

  • Firstly I would recommend discarding the bower.json file. Bower died a long time ago.

    Add a package.json file, with a main property pointing to your plugin file.

    {
        "name": "my-plugin",
        "main": "my-plugin.js",
        "peerDependencies": {
            "jquery": "^3.5.0"
        }
    }
    

    Now within your plugin JavaScript, you'll want to wrap the code within a UMD (Universal Module Definition). This allows your plugin to be loaded through AMD, CommonJS and as a browser global.

    (function (factory) {
        // Universal Module Definition
        if (typeof define === "function" && define.amd) {
            define(["jquery"], factory);
        } else if (typeof module === "object" && module.exports) {
            module.exports = factory(require('jquery'));
        } else {
            // Browser globals
            factory(jQuery);
        }
    })(function ($) {
        $.fn.myPlugin = function () {
            // plugin code here
        };
    });
    

    Webpack supports both AMD and CommonJS definitions, so it'll use the first one it comes across - AMD in this case.

    At this point I would recommend publishing the package to NPM to make it easier to use in your project, but you can also add GitHub repositories as pacakges with yarn:

    yarn add https://github.com/HelloSir/my-plugin
    

    Now you can simply require your plugin in your app code to attach it to jQuery:

    const $ = require('jquery');
    require('my-plugin');
    
    $('.selector').myPlugin();