Magento 2 – Add External JS Library in Custom Module

javascriptmagento2

I would like to add External Library to My Custom Module.

I did below steps.

Vendor/Module/view/frontend/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <link src="Vendor_Module::js/sweetalert.min.js"/>

</head>
<body>
    ......
</body>

Vendor/Module/view/frontend/requirejs-config.js

 var config = {
 map: {
   '*': {
       sweetalert: 'Vendor_Module/js/sweetalert.min',

 }
}};

** Note:-** JS Added I can see it in the source but there's error in the console too.

Uncaught Error: Mismatched anonymous define() module:

Console

Anything missing ??

Best Answer

I think this is because you're adding a require JS module directly to the page via XML rather than adding it as a dependency.

Try adding this as a dependency in your related JS file:

require(['sweetalert'], function(sweetAlert) {
   ... Your code
});