javascripttypescriptfile-loader

Load images with hash in the filename


I am having a problem on loading images. Because it seems an hash is being appended to the filename ( for cache issues I believe)

So I have a image in src/assets/images/image.png directory

In my component I am loading the image this way:

import image from '../assets/images/image.png';

and using like this

<img src={image} ... />

When I console.log(image) I see /static/media/image.f8472220a57d9ac1591b.png.

From what I read I need to add the package file-loader to the project and configure the webpack.config.js. However I dont see that file. But I see the a file .eslintrc.json and tsconfig.json.

In the file .eslintrc.json I added this block inside of rules{}

rules: {
...
"loader": {
      "test": ["*.png", "*.jpeg", "*.jpg", "*.gif"],
      "use": ["file-loader"],
      "exclude": "/node_modules",
      "options": {
        "name": "static/media/[name].[hash:8].[ext]"
      }
    }
}

And it seems to work fine. I can load the images properly.

However when I start the project (yarn start) I see this kind of error

enter image description here

Then I update some code and the error vanish away xD

Is there any way I can prevent this inital error? How can I improve this rule?

In my project I dont see any webpack file :(

Thanks


Solution

  • Your .eslintrc.json is for error checking with ESLint, not for Webpack, and so is different. Removing the code you added will fix the error.

    Because it seems an hash is being appended to the filename (for cache issues I believe)

    Bundlers like Webpack update the hash whenever the file changes, so the new file is loaded. This gets around browser caching. It looks like you are using Create React App, so importing the image should work fine as-is without any extra configuration. file-loader is included with CRA, so don't worry about that.

    import image from '../assets/images/image.png';
    // ...
    <img src={image} />
    

    If you don't want a random hash, move the image to the public/ directory and reference it like so:

    <img src={process.env.PUBLIC_URL + '/images/image.png'} />
    

    You can read more about the public directory at https://create-react-app.dev/docs/using-the-public-folder/#adding-assets-outside-of-the-module-system.


    In my project I dont see any webpack file :(

    Create React App hides it from you for simplicity 🙂 If you need to edit it, run npm run eject, but you can't go back later.