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

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

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

See also:

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