Today we are going to learn about how to add JS, CSS or Less in Magento 2, there are several ways to add JS, CSS or Less in Magento 2 but we are going to cover the most simple and straight forward method. This is the most common requirement for any custom module so hopefully it will help you to add JS, CSS or Less for either all pages or specific pages in Magento 2 based on your specific requirement. Let’s start coding ????

Simply create the file view/frontend/layout/default.xml inside your custom module folder (for example app/code/Scommerce/Custom)

default.xml is for adding JS or CSS or Less files on all the pages

<br>
&lt;?xml version="1.0"?&gt;<br>
&lt;!-- /** * Copyright © 2015 Scommerce Mage. All rights reserved. * See COPYING.txt for license details. */ --&gt;<br>
&lt;page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"&gt;<br> &lt;head&gt;<br> &lt;link src="Scommerce_Custom::custom.js"/&gt;<br> &lt;css src="Scommerce_Custom::custom.css"/&gt;<br> &lt;/head&gt;<br> &lt;body/&gt;<br>
&lt;/page&gt;<br>

If you want to add JS or CSS or Less files on specific page for example product or category page then you need to create view/frontend/layout/catalog_product_view.xml or view/frontend/layout/catalog_category_view.xml respectively inside your custom module folder

catalog_product_view.xml or catalog_category_view.xml files for adding JS or CSS files on product or category pages

<br>
&lt;?xml version="1.0"?&gt;<br>
&lt;!-- /** * Copyright © 2015 Scommerce Mage. All rights reserved. * See COPYING.txt for license details. */ --&gt;<br>
&lt;page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"&gt;<br> &lt;head&gt;<br> &lt;link src="Scommerce_Custom::custom.js"/&gt;<br> &lt;css src="Scommerce_Custom::custom.css"/&gt;<br> &lt;/head&gt;<br> &lt;body/&gt;<br>
&lt;/page&gt;<br>

In regards to less, you just need to create custom.less inside the view/frontend/web folder and Magento will automatically convert your custom.less to custom.css automatically.

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts