How to create a custom module in Magento 2

1.  Create the module directory structure

Inside the app/code directory of your Magento installation, create a directory for your module. For example, if your module is named “CustomModule”, create the following directory structure:

“app/code/Esparksinc/CustomModule”

Here Esparksinc is the vendor name.

2. Create the module configuration file

Inside the module directory, create the file module.xml inside the folder etc

etc/module.xml

 and define the module configuration. For example:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Esparksinc_CustomModule" setup_version="1.0.0"/>
</config>

3. Create the module registration file.

Inside the module directory :

app/code/Esparksinc/CustomModule

 create the file registration.php and register your module. For example:


<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Esparksinc_CustomModule',
    __DIR__
);

4. Enable the module by executing the following command:

 php bin/magento module:enable Esparksinc_CustomModule

5. Run setup upgrade and compile.

php bin/magento setup:upgrade 

php bin/magento cache:flush