Loading External ES6 Script Modules in Magento 2 Ecommerce
How to load external es6 script module in Magento 2 Ecommerce
To add a script with type="module"
in Magento, you can follow the alternative approach you mentioned:
- Create a custom block class in your module or theme. For example, let’s say you have a module called
Your_Module
:
php<?php namespace YourModuleBlock; use MagentoFrameworkViewElementTemplate; class CustomScript extends Template { protected $_template = 'Your_Module::custom_script.phtml'; }
- Create the corresponding template file
custom_script.phtml
in your module or theme’s template directory. For example:
bashapp/code/Your/Module/view/frontend/templates/custom_script.phtml
- In the
custom_script.phtml
file, add your script tag with thetype="module"
attribute:
html<script type="module"> // Your ES6 module code here </script>
- In your layout XML file (e.g.,
default.xml
), add the following code to include the custom block in the head section:
xml<head> <block class="YourModuleBlockCustomScript" name="custom_script" template="Your_Module::custom_script.phtml" /> </head>
- Finally, flush the cache to apply the changes.
With this approach, the custom block will be rendered in the head section of the HTML, and the script with type="module"
will be included.
Please adjust the code according to your module or theme’s structure and naming conventions.
I apologize for any confusion caused earlier, and I appreciate your clarification.
Puneet Kumar Magento Developer
Leave a Reply
Want to join the discussion?Feel free to contribute!