1 | initial version |
Install the crypto
module by running the command npm install crypto
in the terminal.
Create a script in your package.json
file that hashes the files in the assets folder. The script should use the crypto
module to generate a unique hash for each file.
"scripts": {
"postbuild": "node generate-hashes.js"
}
Create a new file in the root of your project called generate-hashes.js
.
In the generate-hashes.js
file, use the following code to generate hashes for the files in the assets folder:
const fs = require('fs');
const crypto = require('crypto');
const hashFile = (filePath) => {
const fileData = fs.readFileSync(filePath);
const hash = crypto.createHash('md5').update(fileData).digest('hex');
return hash;
};
const walkSync = (dir, filelist = []) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = dir + '/' + file;
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
filelist = walkSync(filePath, filelist);
} else {
const hash = hashFile(filePath);
const filename = file.replace(/\.[^/.]+$/, '');
const extension = filePath.split('.').pop();
const hashedFilename = `${filename}.${hash}.${extension}`;
fs.renameSync(filePath, `${dir}/${hashedFilename}`);
}
}
return filelist;
};
const hashAssets = () => {
const assetsPath = './dist/your-app-name/assets';
walkSync(assetsPath);
};
hashAssets();
This code uses the fs
module to read the files in the assets folder, the crypto
module to generate MD5 hashes for each file, and the renameSync()
method to rename the files with their unique hashes.
Save the generate-hashes.js
file.
During deployment, run the postbuild
script defined in your package.json
file. This will execute the generate-hashes.js
file and hash the files in the assets folder.
Update your Angular app to reference the hashed file names instead of the original file names. For example, instead of referencing assets/my-file.jpg
, you would reference assets/my-file.a1b2c3d4.jpg
, where a1b2c3d4
is the unique MD5 hash for that file. This can be done using Angular's built-in mechanisms for referencing assets, such as the assetUrl()
function.