I am attempting to write a function that will return a value for a srcSet attribute, but I am running into an error where React cannot find the image module when required inside a function:
// Error: Cannot find module './img/logo.png'
function App() {
const getSrcSet = ( src ) => {
const ext = '.' + src.split('.').pop();
const _2x = src.replace(ext,'') + '@2x' + ext;
var img1 = require(src).default // ERROR OCCURS HERE
var img2 = require(_2x).default
return img1 + ' 1x, ' + img2 + ' 2x';
}
return (
<img src={require('./img/logo.png').default} srcSet={getSrcSet('./img/logo.png')} alt="logo" />
);
}
--
The function works as expected when I use the "PUBLIC_URL" instead of "require()", but I would prefer to use the former solution if it's possible:
const publicUrl = process.env.PUBLIC_URL
function App() {
const getSrcSet = ( src ) => {
const ext = '.' + src.split('.').pop();
const _2x = src.replace(ext,'') + '@2x' + ext;
return src + ' 1x, ' + _2x + ' 2x';
}
return (
<img src={publicUrl+'img/logo.png'} srcSet={publicUrl+'img/logo.png'} alt="logo" />
);
}
--
NOTE:
I am well aware that I can use the following solution, but I would love to use the getSrcSet function if possible:
import logo from 'logo.png'
import logo2 from 'logo@2x.png'
function App() {
return (
<img src={logo} srcSet={logo + ' 1x, ' + logo2 + ' 2x'} alt="logo" />
);
}
EDIT: Typos
EDIT 2: Added in error message