首页 > 解决方案 > 如何在 PHP 后端使用 Webpack 的捆绑散列?

问题描述

我知道并理解如何/为什么需要缓存清除工作/是必要的。在我的情况下,我的后端代码在 PHP 中,而我的前端代码是在 Webpack 中编译的,我如何使用 Webpack 的哈希方法来清除缓存?

我可以设置 Webpack 以在我的文件名旁边输出一个哈希,但是我怎么知道它输出了哪个哈希呢?如何将此哈希提供给生成 HTML 代码的后端,以便加载正确的资产包?

标签: phphtmlwebpack

解决方案


这是一个相对 hack-y 的解决方案:

你可以写一个这样的函数:

// Defined in: ./includes/functions.inc.php
function returnHashOfMainIn(string $dir): Maybe {
  
  // Get list of all files in given directory ($files is an array of strings).
  $files = scandir("../public/" . $dir); // (this line can be improved)

  // Handling possible failure.
  if ($files === false) {
    return Maybe::return(null); // returns a "Nothing" value.
    // Or simply return a false value if you don't like this typed approach.
  }
  
  // A filter function to discard files that don't start with "main".
  // (change this based on your need).
  $filterFn = function($item) {
    return substr($item, 0, 4) === "main";
  };
  
  // The filtered list of filenames.
  $filtered = array_values(array_filter($files, $filterFn));
  //          ^----------^
  // (used to reset array indices)
  
  if (count($filtered) <= 0) {
    return Maybe::return(null); // returns a "Nothing" value.
  } else {
    
    // Assuming a naming convention of `main.[contenthash].[ext]',
    // you can expect the hash occurring in resulting array's 1st index.
    $expd = explode(".", $filtered[0]);
    
    // Return a "Just string" value (or "Nothing" if $expd[1] is null)
    return Maybe::return($expd[1]);
  }
}

这基本上会给你返回第一个遇到的main文件的哈希(你可以只返回文件名)。

所以假设一个public目录位于目录旁边includes(里面有jscss文件夹):

function makeJsTag() {
  $mJsHash = returnHashOfMainIn("js");
  $tag  = "<script src=\"./js/main.";
  $tag .= $mJsHash->getWithDefault("") . ".js\"></script>";
  return $tag;
}

function makeCssTag() {
  $mCssHash = returnHashOfMainIn("css");
  $tag  = "<link rel=\"stylesheet\" href=\"./css/main.";
  $tag .= $mCssHash->getWithDefault("") . ".css\">";
  return $tag;
}

您可以根据需要将过滤部分替换为任何其他行为(例如main根据上次更改时间对所有找到的文件进行排序 - 使用filectime)。


PS这完全无关紧要,但为了完整起见,这里有一个可能的Maybe类型定义:

abstract class Maybe {
  abstract public function isJust();
  abstract public function getWithDefault($def);
  public static function return($val) {
    if (is_null($val)) {
      return new Nothing;
    } else {
      return new Just($val);
    }
  }
}

final class Just extends Maybe {
  private $value;
  public function __construct($value) {
    $this->value = $value;
  }
  public function isJust() {
    return true;
  }
  public function getWithDefault($_) {
    return $this->value;
  }
}

final class Nothing extends Maybe {
  public function isJust() {
    return false;
  }
  public function getWithDefault($def) {
    return $def;
  }
}

推荐阅读