TransWikia.com

How to add JS library to Magento 2?

Magento Asked by Vlade on January 22, 2021

I need to add the jsPDF library to my Magento 2 Luma theme, so I can use it on the checkout success page.

One Answer

You can create a module using that structure below.

1 - Add you PHTML with the JS call via PHTML

app/code/MyCompany/MyModule/view/frontend/layout/checkout_index_index.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">
    <body>
        <referenceContainer name="content">
            <block class="MagentoFrameworkViewElementTemplate" name="JSPDF" template="MyCompany_MyModule::js_pdf.phtml" />
        </referenceContainer>
    </body>
</page>

2 - Create your PHTML in order to instantiate the JS Library

app/code/MyCompany/MyModule/view/frontend/templates/js_pdf.phtml

<script type="text/javascript">
    //<![CDATA[[
    require(['jquery', 'jspdf' ], function ($, jsPDF) { 
        const pdf = new jsPDF(); 
        $('.print_button_pdf').click(function (){ 
            pdf.text(10, 40, Order); pdf.save('order.pdf');
        });    
    });
    // ]]>
</script>

3 - Call the script via RequireJS

app/code/MyCompany/MyModule/view/frontend/requirejs-config.js

var config = {
    paths: {
        'jsPDF' : ['//unpkg.com/jspdf@latest/dist/jspdf.min', 'MyCompany_MyModule/jspdf.min']
    },
    shim: {
        'jsPDF' : ['jquery']
    }
};

Correct answer by Rafael Corrêa Gomes on January 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP