Magento 2 uses the requireJS library, i.e., javascript file loader, to work with JS files. The developers may, however, require to use custom Javascript for additional features not offered by the default Magento 2.
For example, a custom module requires functionalities such as to select an image, crop an image, display charts, etc. There are many features that can be implemented using Javascript and improve the Magento 2 admin panel. You can also add a custom Phtml file in Magento 2 admin panel to create new layout.
However, to do so, you need to follow the below steps to add custom JS file in Magento 2 admin panel:
Steps to Add Custom JS File in Magento 2 Admin Panel:
1. Create app/code/Vendor/Module/view/adminhtml/requirejs-config.js file with the following code:
var config = { paths: { 'js-file-alias': 'Vendor_Module/js/js-file-name' }, shim: { 'js-file-alias': { deps: ['jquery'] } } };
2. Upload the JavaScript file at app/code/Vendor/Module/view/adminhtml/web/js/
3. Put the following code in your .phtml file to load the JavaScript file
<script> requirejs(['jquery', 'js-file-alias'], function($){ // Your Code }); </script>
4. Run the following commands:
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean
Note: Don’t forget to replace Vendor, Module, js-file-alias, and js-file-name with their respective values.
Follow these steps to add Javascript file in the admin panel for Magento 2. In the same way, you can also update total using JS in Magento 2.
Feel free to post the solution on social media and share it with fellow developers.
Thanks.