ignore-styles
ignore-styles copied to clipboard
How to use asset-manifest on images?
const ignoreStyles = require('ignore-styles');
const register = ignoreStyles.default;
// We also want to ignore all image requests
// When running locally these will load from a standard import
// When running on the server, we want to load via their hashed version in the build folder
const image_extensions = ['.gif', '.jpeg', '.jpg', '.png', '.webp', '.svg'];
const babel_ignore = [
'.css',
'.scss',
'.sass',
'.pcss',
'.stylus',
'.styl',
'.less',
'.sss',
'.gif',
'.jpeg',
'.jpg',
'.png',
'.svg',
'.webp',
'.mp4',
'.webm',
'.ogv',
'.aac',
'.mp3',
'.wav',
'.ogg'
]
// Override the default style ignorer, also modifying all image requests
register(babel_ignore, (mod, filename) => {
if (!image_extensions.find(f => filename.endsWith(f))) {
// If we find a style
return ignoreStyles.noOp();
}
// for images that less than 10k, CRA will turn it into Base64 string, but here we have to do it again
const stats = fs.statSync(filename);
const fileSizeInBytes = stats.size / 1024;
if (fileSizeInBytes <= 10) {
const extension = mod.filename.split(".").pop();
if(extension == "svg") {
mod.exports = `data:image/${extension}+xml;base64,${fs.readFileSync(mod.filename, {
encoding: "base64"
})}`;
} else {
mod.exports = `data:image/${extension};base64,${fs.readFileSync(mod.filename, {
encoding: "base64"
})}`;
}
return ignoreStyles.noOp();
}
// If we find an image
const hash = md5File.sync(filename).slice(0, 8);
const bn = path.basename(filename).replace(/(\.\w{3})$/, `.${hash}$1`);
mod.exports = `/static/media/${bn}`;
});
Using this also serve incorrect url
const _ = require('lodash')
const path = require('path')
register(undefined, (module, filename) => {
if (_.some(['.png', '.jpg'], ext => filename.endsWith(ext))) {
module.exports = path.basename(filename)
}
})
Currently, the hash generated with md5File is not the same as the one used by asset-manifest.json
md5hash : payment.7f8d97e5.svg asset-manifest : 'static/media/payment.04034bb7.svg': '/static/media/payment.04034bb7.svg',
Using react-script 4.0.3
Thank you