webpack-encore怎么在 Laravel 项目中使用
创始人
2024-12-06 17:41:52
0次

安装依赖

首先当然是安装依赖

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 函数

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 '';
  }, $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 '';
  }, $jsonResult['entrypoints'][$entryName]['js']);

  return new HtmlString(implode('', $tags));
}

使用 encore_entry_link_tags 和 encore_entry_script_tags 引用编译的前端资源

在模板里使用前面添加的 helper 函数引用资源,你会发现它比 Laravel 自带的 mix() 函数更方便,只需要一个函数,就可以自动引入 vendor.js 和 app.js 了。


getLocale() }}">

  
  
  

  
  

  {{ config('app.name') }}

  
  {{ encore_entry_link_tags('app') }}



  
  {{ encore_entry_script_tags('app') }}

修改 package.json 中的脚本(scripts)

因为 laravel 项目默认 package.json 中 develop 等相关的脚本都是使用 laravel-mix 的,为了方便日常开发,现在要对它们进行一些调整,改用 webpack-cocore。调整后大致如下,你也可以根据自己实际应用情况进行其它调整

"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

做完前面的这些步骤之后,在终端执行 yarn run hot ,浏览器中输入项目绑定的域名(如 app.test),就可以体验方便高效的 HMR 开发了。

后记

使用 webpack-encore 已经快两个月了,这期间总体说来相当顺利,小坑虽然有,但没什么大坑。去 github 上提 issue,维护成员基本上都很友善耐心,几个小时就会有回复。这种态度也让我对它更加放心了,相信它会折腾得越来越好。虽然 webpack-encore 是作为 Symfony 默认集成工具来设计的,但这并不妨碍它在 Laravel 中发挥强大威力。

相比于 laravel-mi,encore 的 API 以及一些默认配置方面考虑得更为科学和全面,想要配置 vue-loader 或者 ts-loader 之类的,只需要调用相应的方法。另外还有点让我先惊讶的是,他们竟然对 watchOptions.ignored 的默认值也考虑到了,默认忽略 /node_modules/,降低 CPU 占用。当然,更为重要的是,mix4 里因为一些 bug 而无法使用的功能,在 encore 里却正常,如 dynamic import。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...