skip to Main Content

I am using webpack and reactjs

My folder code structure is like this.

src/components
src/css
src/images/myUiButtonImg.png
          /myUiButtonImg_hover.png
          /correct_img.png

There are some png files in images folder and basic.style.module.css is in css folder.

I want to use the png as UI button in component/pain.js

import styles from "../css/basic-styles.module.css";
correct_img from "../images/correct_img.png";
....

<a href="/"><div className={styles.myUIButton}/></a> // try to get png from css.
<img src={{correct_img}}> // this shows correctly.
...

in basic.style.module.css

.myUIButton {
    width:20px;
    background:url("/src/images/myUiButtonImg.png");
}
.myUIButton:hover{
  background:url("/src/images/myUiButtonImg_hover.png");
}

In this case, correct_img shown properly but myUiButtonImg is not.

Is it possible to use the ping in css??

2

Answers


  1. Is the basic.style.module.css in the root folder?

    In the first example you go back into the src folder and navigate to the image.
    In the second you start directly from the src folder. This might be the wrong path src/components/src/images/myUiButtonImg.png.

    To test if the image can be displayed correctly you could try using the absolute path.

    Login or Signup to reply.
  2. Make sure you have these rules in your webpack.config.js. The second rule loads the files ending with *.module.css as css modules otherwise the styles import in your component will be undefined. The third rule loads all the *.png and other asset files.

    rules: [
      {
        test: /.css$/,
        exclude: /.module.css$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
        ],
      },
      {
        test: /.module.css$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader', options: { modules: true } },
        ],
      },
      {
        test: /.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search