用過(guò)Laravel Vite的小伙伴都知道Laravel下使用Vite構(gòu)建前端項(xiàng)目非常方便快捷,而webman下支持需要安裝一大堆依賴配置和修改,本著小而精的理念,特參照Laravel簡(jiǎn)單的實(shí)現(xiàn)類似@vite指令的功能,特分享出來(lái)給需要的朋友使用。
特點(diǎn):
完美兼容Laravel Vite;
同時(shí)支持開(kāi)發(fā)模式和編譯模式;
支持<link rel="preload"預(yù)載;
支持自定義指定構(gòu)建目錄
具體使用:
1、Laravel Vite 安裝及配置使用請(qǐng)參照官方文檔 https://www.laravel.com/docs/9.x/vite
2、在webman下面的/app/function.php文件中增加如下函數(shù)代碼:
/**
* vite助手函數(shù)
* @return string
*/
if (!function_exists('vite')) {
function vite(string | array $entrypoints, string|null $buildDirectory = 'build')
{
$style_pattern = '/\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/';
if (!is_array($entrypoints)) {
$entrypoints = [$entrypoints];
}
$html = '';
if (is_file(public_path('hot'))) {
$host = rtrim(file_get_contents(public_path('hot')));
array_unshift($entrypoints, '@vite/client');
foreach ($entrypoints as $import) {
if (preg_match($style_pattern, $import)) {
$html .= '<link rel="stylesheet" href="' . $host . '/' . $import . '" />';
} else {
$html .= '<script type="module" src="' . $host . '/' . $import . '"></script>';
}
}
} else {
$manifestPath = public_path($buildDirectory . DIRECTORY_SEPARATOR . 'manifest.json');
if (is_file($manifestPath)) {
$manifest = json_decode(file_get_contents($manifestPath), true);
$tags = [];
$preloads = [];
foreach ($entrypoints as $entrypoint) {
if (isset($manifest[$entrypoint])) {
$chunk = $manifest[$entrypoint];
array_push($preloads, $chunk['file']);
array_push($tags, $chunk['file']);
foreach ($chunk['imports'] ?? [] as $import) {
array_push($preloads, $manifest[$import]['file']);
foreach ($manifest[$import]['css'] ?? [] as $css) {
array_push($preloads, $css);
array_push($tags, $css);
}
}
foreach ($chunk['css'] ?? [] as $css) {
array_push($preloads, $css);
array_push($tags, $css);
}
}
}
uasort($preloads, fn ($a, $b) => (preg_match($style_pattern, $a)) ? -1 : 1);
uasort($tags, fn ($a, $b) => (preg_match($style_pattern, $a)) ? -1 : 1);
foreach ($preloads as $preload) {
if (preg_match($style_pattern, $preload)) {
$html .= '<link rel="preload" as="style" href="' . ('/' . $buildDirectory . '/' . $preload) . '" />';
} else {
$html .= '<link rel="modulepreload" as="script" href="' . ('/' . $buildDirectory . '/' . $preload) . '" />';
}
}
foreach ($tags as $tag) {
if (preg_match($style_pattern, $tag)) {
$html .= '<link rel="stylesheet" href="' . ('/' . $buildDirectory . '/' . $tag) . '" />';
} else {
$html .= '<script type="module" src="' . ('/' . $buildDirectory . '/' . $tag) . '"></script>';
}
}
}
}
return $html;
}
}
3、在模板文件中使用
// php原生模版示例:
<?=vite(['resource/css/app.css', 'resource/js/app.js'])?>
// Blade模版示例:
{!! vite(['resource/css/app.css', 'resource/js/app.js']) !!}
// think-template模版示例:
{:vite(['resource/css/app.css', 'resource/js/app.js'])}