看過(guò)我之前寫過(guò)的博客的應(yīng)該知道我一直是 laravel-mix
的死忠粉,有好幾篇文章都是關(guān)于它的。每每提到 laravel-mix 時(shí)更是不吝溢美之詞。然而就在大概一個(gè)月前,我卻決定不再使用它,而轉(zhuǎn)投 webpack-encore 陣營(yíng)。
至于為什么放棄 laravel-mix,主要是因?yàn)樗木S護(hù)狀況堪憂,不僅更新節(jié)奏緩慢,許多 Issue 久懸未決,更重要的是,作者似乎將很多 bug 完全寄希望于 webpack5,哪怕有熱心人士 PR 了,也通常被關(guān)掉,然后回復(fù)說(shuō)“兄 dei,這個(gè)坑等 webpack5 出來(lái)就好了,我之前試過(guò)沒(méi)弄好,估計(jì)你這也填好坑,干脆安分點(diǎn)兒等 webpack5 吧”(不是原話,但差不多是這意思)。但最終讓我下定決心尋求替代方案的,則是這個(gè) Issue ,細(xì)翻源碼,發(fā)現(xiàn)相關(guān)功能依賴的還是 extract-text-webpack-plugin,而這個(gè)包,早在 webpack4 發(fā)布不久就被宣布廢棄了(現(xiàn)在去看它的官方倉(cāng)庫(kù)已經(jīng)被設(shè)置為 archived),而作者似乎完全沒(méi)有使用 mini-css-extract-plugin
的意思。
正所謂愛之深,責(zé)之切,在對(duì) laravel-mix 表示失望之后,我翻出了自己 star 多時(shí)的另一包 webpack-encore,雖說(shuō)很早就 star 了,但之前卻沒(méi)試用過(guò)它,可能也是因?yàn)閷?duì)于 laravel-mix 的偏愛,然而這次,不試便罷,試完之后大有相見恨晚之意。
webpack-encore
是 Symfony 官方的前端集成構(gòu)建工具,同樣是基于 webpack,但它的 API 設(shè)計(jì)得更為友好,而且文檔更完善,當(dāng)然更關(guān)鍵的一點(diǎn)是,坑更少啊……從開始讀它的文檔,倒把手里一個(gè)項(xiàng)目從 laravel-mix 遷移到 webpack-encore,只用了幾個(gè)小時(shí),并且期間相當(dāng)順利。而我遷移的這個(gè)項(xiàng)目,是一個(gè) Laravel 項(xiàng)目,所以下面就分享下,如果在 Laravel 項(xiàng)目中使用 webpack-encore
替代 laravel-mix
。
安裝依賴
首先當(dāng)然是安裝依賴
yarn add -D @symfony/webpack-encore
需要注意的是,webpack-encore
沒(méi)有像 laravel-mix 那樣在自己內(nèi)部依賴 vue-tempplate-compiler
之類的包,所以如果自己項(xiàng)目里用動(dòng)了這些,需要自己在項(xiàng)目里手動(dòng)安裝好。
配置 webpack
在項(xiàng)目根目錄下新建一個(gè) webpack.config.js
文件并在其中配置 webpack-encore
功能(實(shí)際上它最終也是一個(gè)標(biāo)準(zhǔn)的 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 自帶了一個(gè) mix() 函數(shù)用于引用 mix 編譯的資源,與之類似,syfony 也有這樣的函數(shù),而且更為方便。為此你需要在 Laravel 項(xiàng)目中自行實(shí)現(xiàn)這兩方法,下面是我參考 symfony 里相關(guān)源碼改寫的,可能邏輯上并不算完善,但以自己一個(gè)多月的使用情況來(lái)看,它們表現(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ù)引用資源,你會(huì)發(fā)現(xiàn)它比 Laravel 自帶的 mix() 函數(shù)更方便,只需要一個(gè)函數(shù),就可以自動(dòng)引入 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)
因?yàn)?laravel 項(xiàng)目默認(rèn) package.json
中 develop 等相關(guān)的腳本都是使用 laravel-mix 的,為了方便日常開發(fā),現(xiàn)在要對(duì)它們進(jìn)行一些調(diào)整,改用 webpack-cocore
。調(diào)整后大致如下,你也可以根據(jù)自己實(shí)際應(yīng)用情況進(jìn)行其它調(diào)整
"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"
},
運(yùn)行腳本,愉快擼 BUG
做完前面的這些步驟之后,在終端執(zhí)行 yarn run hot ,瀏覽器中輸入項(xiàng)目綁定的域名(如 app.test),就可以體驗(yàn)方便高效的 HMR 開發(fā)了。
后記
使用 webpack-encore
已經(jīng)快兩個(gè)月了,這期間總體說(shuō)來(lái)相當(dāng)順利,小坑雖然有,但沒(méi)什么大坑。去 github 上提 issue,維護(hù)成員基本上都很友善耐心,幾個(gè)小時(shí)就會(huì)有回復(fù)。這種態(tài)度也讓我對(duì)它更加放心了,相信它會(huì)折騰得越來(lái)越好。雖然 webpack-encore 是作為 Symfony 默認(rèn)集成工具來(lái)設(shè)計(jì)的,但這并不妨礙它在 Laravel 中發(fā)揮強(qiáng)大威力。
相比于 laravel-mi
,encore 的 API 以及一些默認(rèn)配置方面考慮得更為科學(xué)和全面,想要配置 vue-loader 或者 ts-loader 之類的,只需要調(diào)用相應(yīng)的方法。另外還有點(diǎn)讓我先驚訝的是,他們竟然對(duì) watchOptions.ignored 的默認(rèn)值也考慮到了,默認(rèn)忽略 /node_modules/,降低 CPU 占用。當(dāng)然,更為重要的是,mix4 里因?yàn)橐恍?bug 而無(wú)法使用的功能,在 encore 里卻正常,如 dynamic import。
總之,如果你已經(jīng)發(fā)現(xiàn)了 laravel-mix
的種種不足但又苦于沒(méi)更好選擇的話,不妨試試 webpack-encore
,相信你會(huì)對(duì)它愛不釋手。
總結(jié)
以上所述是小編給大家介紹的在 Laravel 項(xiàng)目中使用 webpack-encore的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧!