Skip to content

Commit 6d12423

Browse files
authored
[10.x] Allow Vite asset path customization (#49437)
* Allow Vite asset path customization * lint * lint
1 parent 9109198 commit 6d12423

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/Illuminate/Foundation/Vite.php

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ class Vite implements Htmlable
5555
*/
5656
protected $manifestFilename = 'manifest.json';
5757

58+
/**
59+
* The custom asset path resolver.
60+
*
61+
* @var callable|null
62+
*/
63+
protected $assetPathResolver = null;
64+
5865
/**
5966
* The script tag attributes resolvers.
6067
*
@@ -160,6 +167,19 @@ public function useManifestFilename($filename)
160167
return $this;
161168
}
162169

170+
/**
171+
* Resolve asset paths using the provided resolver.
172+
*
173+
* @param callable|null $urlResolver
174+
* @return $this
175+
*/
176+
public function createAssetPathsUsing($resolver)
177+
{
178+
$this->assetPathResolver = $resolver;
179+
180+
return $this;
181+
}
182+
163183
/**
164184
* Get the Vite "hot" file path.
165185
*
@@ -688,7 +708,7 @@ public function content($asset, $buildDirectory = null)
688708
*/
689709
protected function assetPath($path, $secure = null)
690710
{
691-
return asset($path, $secure);
711+
return ($this->assetPathResolver ?? asset(...))($path, $secure);
692712
}
693713

694714
/**

tests/Foundation/FoundationViteTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,33 @@ public function testViteCanOverrideHotFilePath()
657657
$this->cleanViteHotFile('cold');
658658
}
659659

660+
public function testViteCanAssetPath()
661+
{
662+
$this->makeViteManifest([
663+
'resources/images/profile.png' => [
664+
'src' => 'resources/images/profile.png',
665+
'file' => 'assets/profile.versioned.png',
666+
],
667+
], $buildDir = Str::random());
668+
$vite = app(Vite::class)->useBuildDirectory($buildDir);
669+
$this->app['config']->set('app.asset_url', 'https://cdn.app.com');
670+
671+
// default behaviour...
672+
$this->assertSame("https://cdn.app.com/{$buildDir}/assets/profile.versioned.png", $vite->asset('resources/images/profile.png'));
673+
674+
// custom behaviour
675+
$vite->createAssetPathsUsing(function ($path) {
676+
return 'https://tenant-cdn.app.com/'.$path;
677+
});
678+
$this->assertSame("https://tenant-cdn.app.com/{$buildDir}/assets/profile.versioned.png", $vite->asset('resources/images/profile.png'));
679+
680+
// restore default behaviour...
681+
$vite->createAssetPathsUsing(null);
682+
$this->assertSame("https://cdn.app.com/{$buildDir}/assets/profile.versioned.png", $vite->asset('resources/images/profile.png'));
683+
684+
$this->cleanViteManifest($buildDir);
685+
}
686+
660687
public function testViteIsMacroable()
661688
{
662689
$this->makeViteManifest([

0 commit comments

Comments
 (0)