80 lines
2.1 KiB
PHP
80 lines
2.1 KiB
PHP
<?php
|
|
namespace app\lib;
|
|
|
|
use Piko;
|
|
use Piko\View;
|
|
use RuntimeException;
|
|
|
|
class Vite
|
|
{
|
|
private View $view;
|
|
private array $manifest = [];
|
|
private string $viteHost = '';
|
|
private bool $dev = false;
|
|
|
|
public function __construct(View $view)
|
|
{
|
|
$this->view = $view;
|
|
|
|
$manifestFile = Piko::getAlias('@webroot/.vite/manifest.json');
|
|
|
|
if (!file_exists($manifestFile) && !$this->dev) {
|
|
throw new RuntimeException("Manifest file not found ($manifestFile)");
|
|
}
|
|
|
|
if (file_exists($manifestFile) && !$this->dev) {
|
|
$manifest = file_get_contents($manifestFile);
|
|
$this->manifest = json_decode($manifest, true);
|
|
}
|
|
|
|
$this->dev = getenv('VITE_ENV') === 'dev';
|
|
$this->viteHost = getenv('VITE_HOST') ?: '';
|
|
}
|
|
|
|
public function loadEntry(string $entry): void
|
|
{
|
|
if ($this->dev) {
|
|
$this->loadJsFile($entry);
|
|
|
|
return;
|
|
}
|
|
|
|
if (!isset($this->manifest[$entry])) {
|
|
throw new RuntimeException("Entry {$entry} not found in Vite manifest");
|
|
}
|
|
|
|
if (isset($this->manifest[$entry]['file'])) {
|
|
$this->loadJsFile($this->manifest[$entry]['file']);
|
|
}
|
|
|
|
// Load JS imports
|
|
foreach ((array)$this->manifest[$entry]['imports'] as $import) {
|
|
if (isset($this->manifest[$import]['file'])) {
|
|
$this->loadJsFile($this->manifest[$import]['file'], true);
|
|
}
|
|
}
|
|
|
|
// Load Stylesheets
|
|
foreach ((array)$this->manifest[$entry]['css'] as $file) {
|
|
$this->view->registerCSSFile(Piko::getAlias('@web/' . $file));
|
|
}
|
|
}
|
|
|
|
private function loadJsFile($file, $import = false): void
|
|
{
|
|
if ($import && $this->dev) return;
|
|
|
|
if (strpos($file, '.js') === false) return;
|
|
|
|
$url = $this->dev ? rtrim($this->viteHost,'/') . '/' . $file : Piko::getAlias('@web/' . $file);
|
|
|
|
if ($import) {
|
|
$this->view->head[] = '<link rel="modulepreload" href="'. $url. '">';
|
|
|
|
return;
|
|
}
|
|
|
|
$this->view->endBody[] = '<script type="module" crossorigin src="' . $url . '"></script>';
|
|
}
|
|
}
|