How to add JavaScript / CSS / Less with a custom module

css
less
layout
javascript
(Dmitry Fedyuk) #1

Magento (as usual) has many options to do so. I will describe the simplest way.

Create the file view/<area>/layout/default.xml inside your module folder (app/code/Df/Core, for example).
Write «adminhtml» or «frontend» in place of <area>.
An example of default.xml:

<?xml version="1.0"?>
<page
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    layout="admin-1column"
    xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd"
>
    <head>
        <link src="Df_Core::core.js"/>
        <css src="Df_Core::core.css"/>
    </head>
    <body/>
</page>

Write your module name in place of Df_Core.
Place core.js и core.css to the folder view/<area>/web.

Bonus! You can add Less files too!

If you create core.less file instead of core.css, but refer it as <css src="Df_Core::core.css"/> in default.xml above, Magento 2 will intelligently and automatically compile your less file into css!
So you can use Less files in your modules!

See the official article CSS preprocessing for the more info.

1 Like

How to insert some JavaScript to a *.phtml template in the proper way (x-magento-init)
How to add a stylesheet to a page after the layout has already been built?
How to pass parameters from *.phtml to a JavaScript component using x-magento-init
Magento 2 loses the problem Less file name in a «Compilation from source / Cannot read contents from file» error report
How to load JavaScript or stylesheet conditionally depends on backend config settings?
(Dmitry Fedyuk) #2

Please note that Magento 2 supports (but currently never uses in the core) JavaScript execution deferring: How to defer JavaScript execution to page has been loaded using "defer" attribute

0 Likes

(Dmitry Fedyuk) #3

See also:

0 Likes

(Matt Campa) #4

Renaming to .less in a custom module, never compile :S, I located in app\code\Vendor\Modulo\web\css\source

0 Likes