在 Laravel 项目中使用 webpack-encore的方法(2)
新增 php helper 函数
Laravel 自带了一个 mix() 函数用于引用 mix 编译的资源,与之类似,syfony 也有这样的函数,而且更为方便。为此你需要在 Laravel 项目中自行实现这两方法,下面是我参考 symfony 里相关源码改写的,可能逻辑上并不算完善,但以自己一个多月的使用情况来看,它们表现良好。
use Illuminate\Support\HtmlString;
/**
* @param string $entryName
* @return HtmlString
*/
function encore_entry_link_tags(string $entryName): HtmlString
{
$entryPointsFile = public_path('js/entrypoints.json');
$jsonResult = json_decode(file_get_contents($entryPointsFile), true);
if (!array_key_exists('css', $jsonResult['entrypoints'][$entryName])) {
return null;
}
$tags = array_map(function ($item) {
return '<link rel="stylesheet" href="'.$item.'" rel="external nofollow" />';
}, $jsonResult['entrypoints'][$entryName]['css']);
return new HtmlString(implode('', $tags));
}
/**
* @param string $entryName
* @return HtmlString
*/
function encore_entry_script_tags(string $entryName): HtmlString
{
$entryPointsFile = public_path('js/entrypoints.json');
$jsonResult = json_decode(file_get_contents($entryPointsFile), true);
if (!array_key_exists('js', $jsonResult['entrypoints'][$entryName])) {
return null;
}
$tags = array_map(function ($item) {
return '<script src="'.$item.'"></script>';
}, $jsonResult['entrypoints'][$entryName]['js']);
return new HtmlString(implode('', $tags));
}
使用 encore_entry_link_tags 和 encore_entry_script_tags 引用编译的前端资源
在模板里使用前面添加的 helper 函数引用资源,你会发现它比 Laravel 自带的 mix() 函数更方便,只需要一个函数,就可以自动引入 vendor.js 和 app.js 了。
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name') }}</title>
<!-- app.css -->
{{ encore_entry_link_tags('app') }}
</head>
<body>
<div id="app"></div>
{{ encore_entry_script_tags('app') }}
</body>
</html>
修改 package.json 中的脚本(scripts)
因为 laravel 项目默认 package.json 中 develop 等相关的脚本都是使用 laravel-mix 的,为了方便日常开发,现在要对它们进行一些调整,改用 webpack-cocore。调整后大致如下,你也可以根据自己实际应用情况进行其它调整
内容版权声明:除非注明,否则皆为本站原创文章。
