根据被接受的答案,您可以使用Laravel Mix为资产添加版本号,但OP说他的资产代码目前位于public文件夹中。要使用Laravel Mix的方式,他需要将所有资产(js、css)从public转移到resource,添加.gitignore以忽略public中的资产文件夹,运行git rm -r --cached /public以完全从缓存中删除它们,然后运行npm run prod将资源生成到public中。这样,OP将继续使用Laravel的方式进行工作。
然而,如果OP确实想继续在public文件夹中工作(当前有太多资产),他/她可以使用composer包tooleks/laravel-asset-version。
您可以参考此处的
Github存储库。
注意:
您还可以在config/assets.php中添加版本号,或者可以在.env文件中添加版本号。
config/assets.php
<?php
return [
...
'version' => env('VERSION', '0.0.1'),
];
运行
npm i dotenv
来安装dotenv(如果尚未安装)。
在根目录中进行必要的更改,并创建
version.js
文件。该文件将负责使用npm命令在.env中动态生成版本号。
version.js
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
const today = new Date();
const year = today.getFullYear().toString().padStart(4, '0');
const month = (today.getMonth() + 1).toString().padStart(2, '0');
const day = today.getDate().toString().padStart(2, '0');
const key = 'VERSION';
const value = `${year}.${month}.${day}`;
const envFileContent = fs.readFileSync('.env', 'utf8');
const lines = envFileContent.split('\n');
let keyFound = false;
const updatedLines = lines.map((line) => {
const [lineKey, lineValue] = line.split('=');
if (lineKey === key) {
keyFound = true;
return `${lineKey}=${value}`;
}
return line;
});
if (!keyFound) {
updatedLines.push('');
updatedLines.push(`${key}=${value}`);
}
const updatedEnvConfig = updatedLines.join('\n');
fs.writeFileSync('.env', updatedEnvConfig);
console.log(`Successfully updated ${key} in the .env file.`);
然后在你的 package.json 中添加
"scripts": {
...
"version" : "node version.js"
},
现在你可以运行
npm run version
,将版本号以
yyyy.mm.dd
的格式添加到 .env 文件中。如果需要的话,可以更改格式。
如果一切设置正确,你应该看到类似于
https://website.domain/path/to/asset.css?v=yyyy.mm.dd
的东西。
md5
或更安全的bcrypt
进行哈希处理。 - Elwin