Skip to content

Commit f2a5ee4

Browse files
Merge pull request #5 from JuKra00/feature/asset-css
Add cssAsset method to get associated css files to an asset
2 parents 33757d4 + 0b3385f commit f2a5ee4

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,15 @@ These assets will now be processed by Vite when running `npm run build`. You can
188188
<img src="<?= vite()->asset('assets/images/logo.png') ?>">
189189
```
190190

191+
## Associated CSS Files
192+
In some cases, you may want to include a Javascript file conditionally using the `vite()->asset()` method. Associated CSS files will not be included automatically. You can use the `vite()->assetCss()` method, which will return an array of URLs for the CSS files associated with a given asset:
193+
194+
```php
195+
<?php foreach (vite()->assetCss('assets/js/my-component.js') as $cssFile): ?>
196+
<link rel="stylesheet" href="<?= $cssFile ?>">
197+
<?php endforeach ?>
198+
```
199+
191200
## Arbitrary Attributes
192201
If you need to include additional attributes on your script and style tags, such as the `data-turbo-track` attribute, you may specify them via the plugin options.
193202

Vite.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,32 @@ public function asset(string $asset, string $buildDirectory = null): string
382382
return url($buildDirectory . '/' . $chunk['file']);
383383
}
384384

385+
/**
386+
* Get URL(s) of CSS file(s) associated with an asset.
387+
*
388+
* @param string $asset The asset to get CSS for
389+
* @param string|null $buildDirectory Optional build directory
390+
* @return array Array of CSS file URLs
391+
*/
392+
public function assetCss(string $asset, string $buildDirectory = null): array
393+
{
394+
$buildDirectory ??= $this->buildDirectory;
395+
396+
if ($this->isRunningHot()) {
397+
return [];
398+
}
399+
400+
$chunk = $this->chunk($this->manifest($buildDirectory), $asset);
401+
$cssFiles = [];
402+
403+
// Get direct CSS files
404+
foreach ($chunk['css'] ?? [] as $cssFile) {
405+
$cssFiles[] = url($buildDirectory . '/' . $cssFile);
406+
}
407+
408+
return $cssFiles;
409+
}
410+
385411
/**
386412
* Generate React refresh runtime script.
387413
*/

0 commit comments

Comments
 (0)