In this post, we will see how to add custom css and cusom js to our custom module in Magento 2. I am assuming that you have your custom module and if you don’t have click here and first create your custom module.

Magento 2 custom css and custom js custom module

Magento 2 css and js custom module

So we have a file Vky/Test/view/frontend/layout/test_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vky\Test\Block\Test" name="test.list" template="test.phtml">
            </block>
        </referenceContainer>
    </body>
</page>

Add custom CSS

To add custom CSS we use <css src="Vky_Test::css/custom_test.css" />

Create Vky/Test/view/frontend/web/css/custom_test.css

.page-title{
	color: #f47b20 !important;
}

 

Add custom JS

To add custom JS we use <script src="Vky_Test::js/custom_test.js"/>

Create Vky/Test/view/frontend/web/js/custom_test.js

require([
"jquery"
], function($){
	$(document).ready(function() {
    	  alert("Hi, I am from custom_test.js");
	});
});

Let’s say we want to add our custom css and js to head. So our edited test_index_index.xml will be like below.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
	    <css src="Vky_Test::css/custom_test.css" />
	    <script src="Vky_Test::js/custom_test.js"/>
	</head> 
    <body>
        <referenceContainer name="content">
            <block class="Vky\Test\Block\Test" name="test.list" template="Vky_Test::test.phtml">
            </block>
        </referenceContainer>
    </body>
</page>

Now open the SSH terminal and go to the root directory of your project then run the command

php bin/magento cache:flush

It’ done. Check your module’s frontend page you should have your custom css and js in it. Open the page www.magento2.com/test right-click and select view page source then search for your custom files like custom_test.css or custom_test.js

Click below link to see
Create a table using InstallSchema and UpgradeSchema in magento 2?

Now once you know this is how it works then you don’t have to create the same files again and again for your every custom module. You can generate a custom module code from my module creator.

Click here for the Magento 2 Module Creator.

No Comments

Post A Comment