看過我之前寫過的博客的應該知道我一直是 laravel-mix
的死忠粉,有好幾篇文章都是關于它的。每每提到 laravel-mix 時更是不吝溢美之詞。然而就在大概一個月前,我卻決定不再使用它,而轉投 webpack-encore 陣營。
至于為什么放棄 laravel-mix,主要是因為它的維護狀況堪憂,不僅更新節(jié)奏緩慢,許多 Issue 久懸未決,更重要的是,作者似乎將很多 bug 完全寄希望于 webpack5,哪怕有熱心人士 PR 了,也通常被關掉,然后回復說“兄 dei,這個坑等 webpack5 出來就好了,我之前試過沒弄好,估計你這也填好坑,干脆安分點兒等 webpack5 吧”(不是原話,但差不多是這意思)。但最終讓我下定決心尋求替代方案的,則是這個 Issue ,細翻源碼,發(fā)現(xiàn)相關功能依賴的還是 extract-text-webpack-plugin,而這個包,早在 webpack4 發(fā)布不久就被宣布廢棄了(現(xiàn)在去看它的官方倉庫已經被設置為 archived),而作者似乎完全沒有使用 mini-css-extract-plugin
的意思。
正所謂愛之深,責之切,在對 laravel-mix 表示失望之后,我翻出了自己 star 多時的另一包 webpack-encore,雖說很早就 star 了,但之前卻沒試用過它,可能也是因為對于 laravel-mix 的偏愛,然而這次,不試便罷,試完之后大有相見恨晚之意。
webpack-encore
是 Symfony 官方的前端集成構建工具,同樣是基于 webpack,但它的 API 設計得更為友好,而且文檔更完善,當然更關鍵的一點是,坑更少啊……從開始讀它的文檔,倒把手里一個項目從 laravel-mix 遷移到 webpack-encore,只用了幾個小時,并且期間相當順利。而我遷移的這個項目,是一個 Laravel 項目,所以下面就分享下,如果在 Laravel 項目中使用 webpack-encore
替代 laravel-mix
。
安裝依賴
首先當然是安裝依賴
yarn add -D @symfony/webpack-encore
需要注意的是,webpack-encore
沒有像 laravel-mix 那樣在自己內部依賴 vue-tempplate-compiler
之類的包,所以如果自己項目里用動了這些,需要自己在項目里手動安裝好。
配置 webpack
在項目根目錄下新建一個 webpack.config.js
文件并在其中配置 webpack-encore
功能(實際上它最終也是一個標準的 webpack 配置文件),以最基本的玩法為例。
const Encore = require('@symfony/webpack-encore')
Encore
// directory where compiled assets will be stored
.setOutputPath('public/js/')
// public path used by the web server to access the output path
.setPublicPath('/js')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Add 1 entry for each "page" of your app
* (including one that's included on every page - e.g. "app")
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if you JavaScript imports CSS.
*/.addEntry('app', './resources/js/app.js')
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild().enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
.enableVueLoader()
.enableSassLoader(options => {
options.implementation = require('sass')
})
// fetch the config, then modify it!
const config = Encore.getWebpackConfig()
// export the final config
module.exports = config
新增 php helper 函數(shù)
Laravel 自帶了一個 mix() 函數(shù)用于引用 mix 編譯的資源,與之類似,syfony 也有這樣的函數(shù),而且更為方便。為此你需要在 Laravel 項目中自行實現(xiàn)這兩方法,下面是我參考 symfony 里相關源碼改寫的,可能邏輯上并不算完善,但以自己一個多月的使用情況來看,它們表現(xiàn)良好。
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 函數(shù)引用資源,你會發(fā)現(xiàn)它比 Laravel 自帶的 mix() 函數(shù)更方便,只需要一個函數(shù),就可以自動引入 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 的,為了方便日常開發(fā),現(xiàn)在要對它們進行一些調整,改用 webpack-cocore
。調整后大致如下,你也可以根據(jù)自己實際應用情況進行其它調整
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development encore dev",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "encore dev-server --port=9001 --hot",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production encore production"
},
運行腳本,愉快擼 BUG
做完前面的這些步驟之后,在終端執(zhí)行 yarn run hot ,瀏覽器中輸入項目綁定的域名(如 app.test),就可以體驗方便高效的 HMR 開發(fā)了。
后記
使用 webpack-encore
已經快兩個月了,這期間總體說來相當順利,小坑雖然有,但沒什么大坑。去 github 上提 issue,維護成員基本上都很友善耐心,幾個小時就會有回復。這種態(tài)度也讓我對它更加放心了,相信它會折騰得越來越好。雖然 webpack-encore 是作為 Symfony 默認集成工具來設計的,但這并不妨礙它在 Laravel 中發(fā)揮強大威力。
相比于 laravel-mi
,encore 的 API 以及一些默認配置方面考慮得更為科學和全面,想要配置 vue-loader 或者 ts-loader 之類的,只需要調用相應的方法。另外還有點讓我先驚訝的是,他們竟然對 watchOptions.ignored 的默認值也考慮到了,默認忽略 /node_modules/,降低 CPU 占用。當然,更為重要的是,mix4 里因為一些 bug 而無法使用的功能,在 encore 里卻正常,如 dynamic import。
總之,如果你已經發(fā)現(xiàn)了 laravel-mix
的種種不足但又苦于沒更好選擇的話,不妨試試 webpack-encore
,相信你會對它愛不釋手。
總結
以上所述是小編給大家介紹的在 Laravel 項目中使用 webpack-encore的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下吧!