How to create Magento 2 custom module with include Css and Js ?
2 Answers
I Hope this is useful for You,
add your css file to
app/code/vendor/module/view/frontend/web/css/mycss.css
mycss.css
body{
background-color:green;
}
add your Js file
app/code/vendor/module/view/frontend/web/js/myjs.js
myjs.js:
require([
"jquery"
], function($){
$(document).ready(function() {
alert("Hello");
});
});
Reference: http://webkul.com/blog/magento2-how-to-add-css-and-js-file-in-module/ http://www.webspeaks.in/2016/03/how-to-add-css-and-js-in-magento-2-custom-module.html
Then add css and Js File to Your layout File.
app/code/vendor/module/view/frontend/layout/test_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_layout.xsd">
<head>
<css src="Vendor_Module::css/mycss.css" />
<script src="Vendor_Module::js/myjs.js"/>
</head>
<body>
<referenceContainer name="content">
<block class="Vendor\Module\Block\class" template="Vendor_Module::class.phtml"/>
</referenceContainer>
</body>
</page>
Remove this folder
rm -rf var/cache/*
rm -rf var/page_cache/*
Remove pub/static
rm -rf pub/static/*
or
If throw any error, via remove pub/static in terminal,
Go to **<Magento root Dir>** via file manager the **remove pub/static** directory.
not using terminal to remove **pub/static** **folder**.
Next generate Static Content:
bin/magento setup:static-content:deploy
Or
php bin/magento setup:static-content:deploy
Now, try, Its worked for me.
-
-
2You forgot to put
php
beforebin/magento setup:static-content:deploy
So, last command is:php bin/magento setup:static-content:deploy
– WaPoNeDec 1, 2016 at 15:11 -
@WaPoNe I use
bin/magento setup:static-content:deploy
its is also works , i think windows only usephp bin/magento setup:static-content:deploy
Dec 1, 2016 at 15:23 -
6@Rajkumar.E when you try to call your css/js, you have to specify the vendorName_moduleName also before css/js name:
<css src="vendorName_moduleName::css/mycss.css" />
and<script src="vendorName_moduleName::js/myjs.js"/>
– WaPoNeDec 1, 2016 at 15:59 -
3A word of warning. When running
rm -rf pub/static
for apache users, yourpub/static/.htaccess
file may be removed causing console logs about missing files.– DaveJan 19, 2017 at 1:49
Try this
Create the view/<area>/layout/default.xml file in your module folder, which can be app/code/Df/Core, for instance.
Replace <area> with adminhtml or frontend
default.xml should look like:
<?xml version="1.0"?>
<page
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
layout="admin-1column"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"
>
<head>
<link src="Df_Core::core.js"/>
<css src="Df_Core::core.css"/>
</head>
<body>
<body/>
</page>
put the core.js and core.css files to the view/<area>/web folder.