Magento 2 Add Library JavaScript File

Quick post to show you how to add in a third-party library via RequireJS. In this example I will be using the popular carousel library Slick Slider.

Configuring RequireJS

First add your third-party library file to your theme directory,

app/design/frontend/<VendorName>/<ThemeName>/js/vendor/slick.min.js

Next we need to configure our RequireJS. If you haven’t already got a configuration file setup create a new file under your theme directory called requirejs-config.js:

app/design/frontend/<VendorName>/<ThemeName>/requirejs-config.js

Now add the following contents:

var config = {
    paths: {
        'jquery/slick': 'js/vendor/slick.min'
    },
    shim: {
        'jquery/slick': {
            deps: ['jquery'],
            exports: 'jQuery.fn.slick'
        }
    }
};

Here we have created the name jquery/slick and passed in the location of the script file. I find it’s good practice when using jQuery plugins to use the naming convention jquery/<name>.

paths:

The paths config is used to set a path for your resource location. Do not include the ‘.js’ part for the path.

shim:

The shim config is used to configure dependencies for the library. The exports part is used to tell RequireJS what to look for to know the script loaded correctly. The value must be a variable defined within the library.

Now we have everything configured all that’s left to do is require the library when you need to. There are different methods available to us as detailed in the Magento 2 documentation. Also check out my previous blog post on Calling and Initializing JavaScript.

Whichever method you choose the contents of the script is typically the same, by passing in the “name” you created in the RequireJS configuration file as a dependency.

Require:

require([
    'jquery',
    'jquery/slick'
], function($) {
    'use strict';

    $(function() {
        $('.selector').slick();
    });
});

Define:

define([
    'jquery',
    'jquery/slick',
], function($) {
    'use strict';

    var carousel = function(config, element) {
        $(element).slick();
    };

    return carousel;
});

The main part of including any library is the RequireJS configuration, once you have this setup you just need to include it as a dependency within your scripts.