As per the accepted answer, you can use laravel mix to add version number to the assets but OP said that his assets code are currently in the public folder. To use the laravel mix way, he needs to transfer all the assets(js, css) from public to resource, add .gitignore
to ignore assets folder in public, run git rm -r --cached /public
to completely remove them from the cache then run npm run prod
to generate the assets from resource to public. This way, OP will now continue working using the laravel way.
However if OP does want to continue working in the public folder (too many assets right now), he/she can use the composer package tooleks/laravel-asset-version
.
You can use this Github repo for reference.
Note:
You can also add the version number in config/assets.php or you can add the version number in the .env file.
config/assets.php
<?php
return [
...
'version' => env('VERSION', '0.0.1'),
];
run npm i dotenv
to install dotenv if not yet installed
Make the necessary changes and create version.js
in the root folder. This file will be responsible to generate the version number in the .env dynamically using npm command.
version.js
const fs = require('fs');
const dotenv = require('dotenv');
// Load the .env file
dotenv.config();
// Specify the key and value you want to update or add
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}`;
// Update the .env file
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) {
// Add a line break before adding the variable
updatedLines.push('');
// Add the key-value pair
updatedLines.push(`${key}=${value}`);
}
const updatedEnvConfig = updatedLines.join('\n');
fs.writeFileSync('.env', updatedEnvConfig);
console.log(`Successfully updated ${key} in the .env file.`);
Then add in your package.json
"scripts": {
...
"version" : "node version.js"
},
Now you can run npm run version
to add version number to the .env file with format yyyy.mm.dd
. Change the format if needed.
If everything is set corretly, you should see something like https://website.domain/path/to/asset.css?v=yyyy.mm.dd