React images paths are working with the img tag, but not working in css

53 views Asked by At

I'm struggling with image serving in React.

<img src="/images/test.jpg" alt="" /> works (in jsx/html).

background-image: url("/images/test.jpg"); does not work (in css).

I've never had these problems with nextjs, but for various reasons, I can't use that on this project.

I have a directory structure of

/src
/src/styles/
/src/styles/_globals
/src/public
/src/public/images

I've installed react-app-rewired, and created several files:

//config-overrides.js
const path = require('path');

module.exports = function override(config, env) {
  if (env === "production") {
    config.output = {
            ...config.output,
            // Set the publicPath to '/'
            publicPath: '/'
        };
    }

  config.resolve = {
    ...config.resolve,
    alias: {
      ...config.resolve.alias,      
      'images': path.resolve(__dirname, 'public/images')
    },
  };

  return config;
};
//tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "images/*": ["./public/images/*"]      
    }
  }
}
//tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": "./",       
    "incremental": true,
    "baseUrl": ".", 
    "paths": {
      "@components/*": ["src/components/*"]      
    }
  },
  "include": ["**/*.ts", "**/*.tsx", "declarations.d.ts"]  
}

and I've updated package.json scripts to

    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",

I'm getting the error

Compiled with problems:
×
ERROR in ./src/styles/_globals.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles/_globals.scss) 8:36-82
Module not found: Error: Can't resolve '../images/test.jpg' in 'C:\Users\jon\Documents\GitHub\project\src\styles'

I'm struggling, and any help is very much appreciated.

Thanks -

3

There are 3 answers

0
Jon On BEST ANSWER

I figured it out:

background-image: url("~/public/images/test.jpg");

Thank you to Wallace for your answer, as it got me searching down the right path. However, I don't understand why it works and if anyone wants to chime in it would be very helpful.

1
Wallace Nascimento On

You need to use require, change:

url("../images/test.jpg").

to:

url(require("../images/test.jpg")).
1
Sethu Ravichandran On

Try using an absolute path, from your project's root directory

background-image: url("/src/public/images/test.jpg");