How to Get Module’s view directory image or js full path using Magento 2?

You can retrieve the full path of the Module’s static asset like Images, Javascript, or CSS file path using Magento 2.

If you want to get the full path of the view directory for the frontend or backend area, You need to use Magento\Framework\View\Asset\Repository class to achieve the task.

Let’s simple example for a demo, Our Module name is Jesadiya_Holiday with static assets available in the view directory of the module.

holiday1.png file resides under the path,
app\code\Jesadiya\Holiday\view\frontend\web\images\holiday1.png

You want to get the full path using Magento for Image holiday1.png,

<?php
namespace Jesadiya\Holiday\Model;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\Framework\View\Asset\Repository;

class GetViewDirectoryPath
{
    public function __construct(
        private LoggerInterface $logger,
        private Repository $assetRepository
    ) {
    }

    /**
     * Get Image full path from view directory
     */
    public function getImageFullPath()
    {
        $fileId = 'Jesadiya_Holiday::images/holiday1.png';

        $params = [
            'area' => 'frontend' //for admin area its backend
        ];

        $asset = $this->assetRepository->createAsset($fileId, $params);

        $imageFullPath = null;
        try {
            $imageFullPath = $asset->getSourceFile();
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage());
        }

        return $imageFullPath;
    }
}

Call function using,
echo $this->getImageFullPath();

Output: Full Image path from view directory of image folder,
/var/www/html/magento246/app/code/Jesadiya/Holiday/view/frontend/web/images/holiday1.png

You can also fetch JS full path using the above function, You need to pass $fileId as the JS path,

$fileId = ‘Jesadiya_Holiday::js/custom.js’;
Using the above way, You got the Javascript full path from the module.

You need to pass $params Array as the area code like frontend or backend.