php - 如何在 PHP 后端使用 Webpack 的捆绑散列?
问题描述
我知道并理解如何/为什么需要缓存清除工作/是必要的。在我的情况下,我的后端代码在 PHP 中,而我的前端代码是在 Webpack 中编译的,我如何使用 Webpack 的哈希方法来清除缓存?
我可以设置 Webpack 以在我的文件名旁边输出一个哈希,但是我怎么知道它输出了哪个哈希呢?如何将此哈希提供给生成 HTML 代码的后端,以便加载正确的资产包?
解决方案
这是一个相对 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
(里面有js
和css
文件夹):
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;
}
}
推荐阅读
- javascript - 让 CSS 按钮在单击时变为绿色并保持绿色
- mysql - 当条件不满足时,MySQL Force 'WHERE' 显示 null
- python - TensorFlow 的正则化器中的 scale 代表什么?
- visual-studio-code - 在“/Users/userName”中找不到名为“pubspec.yaml”的文件
- ios - 在 SWIFT 4 中将 JSON 数据移出本地范围
- django - Django:inlineformset '属性没有与之关联的文件' 错误
- mariadb - Mariadb 10.3.8:从 MariaDB 存储库安装,缺少文件?
- android - Android:从 AsyncTask 请求位置权限
- c++ - 如何在 C++ 中使用 libcurl 发送和接收 POST 请求?
- html - VBA网页抓取代码错误与宏链接