在 Laravel 項(xiàng)目中使用 webpack-encore的方法
看過我之前寫過的博客的應(yīng)該知道我一直是 laravel-mix
的死忠粉,有好幾篇文章都是關(guān)于它的。每每提到 laravel-mix 時(shí)更是不吝溢美之詞。然而就在大概一個(gè)月前,我卻決定不再使用它,而轉(zhuǎn)投 webpack-encore 陣營。
至于為什么放棄 laravel-mix,主要是因?yàn)樗木S護(hù)狀況堪憂,不僅更新節(jié)奏緩慢,許多 Issue 久懸未決,更重要的是,作者似乎將很多 bug 完全寄希望于 webpack5,哪怕有熱心人士 PR 了,也通常被關(guān)掉,然后回復(fù)說“兄 dei,這個(gè)坑等 webpack5 出來就好了,我之前試過沒弄好,估計(jì)你這也填好坑,干脆安分點(diǎn)兒等 webpack5 吧”(不是原話,但差不多是這意思)。但最終讓我下定決心尋求替代方案的,則是這個(gè) Issue ,細(xì)翻源碼,發(fā)現(xiàn)相關(guān)功能依賴的還是 extract-text-webpack-plugin,而這個(gè)包,早在 webpack4 發(fā)布不久就被宣布廢棄了(現(xiàn)在去看它的官方倉庫已經(jīng)被設(shè)置為 archived),而作者似乎完全沒有使用 mini-css-extract-plugin
的意思。
正所謂愛之深,責(zé)之切,在對(duì) laravel-mix 表示失望之后,我翻出了自己 star 多時(shí)的另一包 webpack-encore,雖說很早就 star 了,但之前卻沒試用過它,可能也是因?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
沒有像 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è)多月的使用情況來看,它們表現(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è)月了,這期間總體說來相當(dāng)順利,小坑雖然有,但沒什么大坑。去 github 上提 issue,維護(hù)成員基本上都很友善耐心,幾個(gè)小時(shí)就會(huì)有回復(fù)。這種態(tài)度也讓我對(duì)它更加放心了,相信它會(huì)折騰得越來越好。雖然 webpack-encore 是作為 Symfony 默認(rèn)集成工具來設(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 而無法使用的功能,在 encore 里卻正常,如 dynamic import。
總之,如果你已經(jīng)發(fā)現(xiàn)了 laravel-mix
的種種不足但又苦于沒更好選擇的話,不妨試試 webpack-encore
,相信你會(huì)對(duì)它愛不釋手。
總結(jié)
以上所述是小編給大家介紹的在 Laravel 項(xiàng)目中使用 webpack-encore的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧!
相關(guān)文章
thinkphp3.x自定義Action、Model及View的簡單實(shí)現(xiàn)方法
這篇文章主要介紹了thinkphp3.x自定義Action、Model及View的簡單實(shí)現(xiàn)方法,結(jié)合實(shí)例形式詳細(xì)分析了thinkPHP3.x自定義模型、視圖及控制器的具體步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-05-05phpstorm配置php運(yùn)行環(huán)境的詳細(xì)步驟
這篇文章主要介紹了phpstorm配置php運(yùn)行環(huán)境的詳細(xì)步驟,首先安裝phpstrom,按照提示的步驟一步一步來就行,文中給大家介紹了phpstorm的簡單配置,需要的朋友可以參考下2023-09-09php compact 通過變量創(chuàng)建數(shù)組
php compact函數(shù)用于創(chuàng)建數(shù)組,該函數(shù)創(chuàng)建數(shù)組比較特殊,compact函數(shù)參數(shù)將接受一個(gè)或多個(gè)變量,然后將變量的名稱作為該創(chuàng)建數(shù)組的索引,變量值作為該創(chuàng)建數(shù)組的值,然后返回創(chuàng)建完成的數(shù)組。本文章向大家講解compact函數(shù)的基本語法及使用實(shí)例。需要的碼農(nóng)可以參考一下。2016-11-11PHP中__set()實(shí)例用法和基礎(chǔ)講解
在本篇文章里小編給大家整理了關(guān)于HP中__set()實(shí)例用法和基礎(chǔ)講解,對(duì)此有需要的朋友們可以學(xué)習(xí)參考下。2019-07-07php調(diào)用百度人臉識(shí)別接口查詢數(shù)據(jù)庫人臉信息實(shí)現(xiàn)驗(yàn)證登錄功能
這篇文章主要介紹了php調(diào)用百度人臉識(shí)別接口查詢數(shù)據(jù)庫人臉信息實(shí)現(xiàn)驗(yàn)證登錄功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01Laravel?Many-To-Many多對(duì)多關(guān)系模式示例詳解
這篇文章主要為大家介紹了Laravel?Many-To-Many多對(duì)多關(guān)系模式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06