Skip to content

Requirejs

Declaring External Javascript library

In theme

Under app/design/{area}/{package}/{theme-name}/ create a file called requirejs-config.js to include simple javascript file which holds some javascript functions

you need to declare that file first. Inside requirejs-config.js insert

var config = {
    map: {
        '*': {
            edmondscommerce: 'js/custom'
        }
    }
};

js/custom will be converted to file location under app/design/{area}/{package}/{theme-name}/web/js/custom.js

So now require.js knows about your custom javascript file, however you need to initialize it.

There is couple ways of doing that, follow the link, to get more methods on magento 2 javascript initialization.

In extension

Under app/code/{namespace}/{modulename}/view/{design-area} create a file called requirejs-config.js to include simple javascript file which holds some javascript functions

you need to declare that file first. Inside reuirejs-config.js insert

var config = {
    map: {
        '*': {
            // sometitle : 'Namespace_Modulename/js/path/to/file'
            clipboard: 'EdmondsCommerce_DeliveryDetails/js/clipboard.min'
        }
    }
};

EdmondsCommerce_DeliveryDetails/js/clipboard.min will be converted to file location under app/code/{namespace}/{modulename}/view/{design-area}/web/js/clipboard.min.js

And then you need to initialize it in template file using the snippet

<script>
    require([
        'clipboard'
    ], function (Clipboard) {
        var copy = new Clipboard('.btn');
    });
</script>

Note

Be aware of javascript initialization types, because for example for clipboard.js Initialization type like <script type="text/x-magento-init"> won't work because it has direct interaction with elements This type you can use only when To call a JS component on a HTML element without direct access to the element or with no relation to a certain element

Good reads

Alanstorm Magento 2 and RequireJS