问题
I'm using next.js with file-loader and url-loader to load in images into my React components like below:
import background from '@/assets/mountain-shot.jpg';
const Section = styled.section`
background-color: #f3f3f3;
background-image: url(${background});
background-size: cover;
background-position: center;
box-shadow: inset 2px 33px 97px -21px rgba(0,0,0,0.75);
position: relative;
`;
As you can see I'm importing an image and outputting it in the styled components. If I remove the background image it loads with the background #f3f3f3 and then I put back in the background image the image does load. It is at this point that I do a refresh that the image and all other styling in this block disappears.
I figured this might be an issue with my next.config setup so I will paste this below here:
config.module.rules.push({
test: /\.(woff(2)?|ttf|eot|gif|png|jp(e*)g)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]',
},
},
],
});
We are using Next.js to do our SSR this might be worth mentioning.
When I console log background I get this value on the first load where it works:
/_next/webpack/images/b3f1c5846e75c47d10b0fa02957ac1b4-mountain-shot.jpg
And on the second load where it the styling disappears I get exactly the same url but it does not appear.
** update **
I've noticed now that when the image appears on the first time you can make changes and it will still be viewable. It isn't actaully until you do a hard/soft refresh that is disappears.
回答1:
The url has to be a string inside a string:
url("${background}");
来源:https://stackoverflow.com/questions/51932723/url-loader-loading-my-background-image-once-then-after-refreshing-the-page-it-f