React-starter-kit: How to add image in css?

Created on 3 Nov 2016  路  7Comments  路  Source: kriasoft/react-starter-kit

After https://github.com/kriasoft/react-starter-kit/commit/048e67f957f4b0eed7e67094544eee1b47083fe4
I have error "Cannot resolve module image.png" when css file contains background: url('./image.png')

CSS bug

Most helpful comment

When you remove the plugin 'postcss-url' from webpack-config it works again.

All 7 comments

When you remove the plugin 'postcss-url' from webpack-config it works again.

Thanks, it solved my problem!

Please keep it opened until the problem exists in the master branch

You can keep postcss in webpack, My resolve is:

  • You create folder inside public/img and place your img there (ex: public/img/Header/logo.png)
  • Then, in you css you insert img by format url('/img/Header/logo.png')

I think postcss-url should be removed or it should be documented somewhere that when one wants to use paths in css and have webpack process them, postcss-url must be disabled. The problem is that postcss-url rewrites url('./img.jpg') to url('img.jpg'); which is fine normally, but now css-loader doesn't recognize the url import properly.

You can also escape the relative path like this url('\./img.jpg') it will stop the postcss-url rewrite.

You can use custom transform function according to postcss-url's doc.

  require('postcss-url')({
      url: (url, decl, from, dirname) => {
        // Should not rewrite data urls
        if (isDataURL(url)) {
          return url;
        }

        // Handle relative path from external css.
        // e.g. @import 'font-awesome/css/font-awesome.css'. Which will resolve icon fonts path to
        // 'relative-path-to-node_modules/font-awesome/fonts/...'
        if (path.relative(from, dirname)) {
          return path.join(path.relative(from, dirname), url);
        }

       // Return raw url. Resolve the path rewrites
        return url;
      },
    }),
Was this page helpful?
0 / 5 - 0 ratings