8

I have just started React JS, but I have a problem and despite my research I can not get results, I have tried many ways, but I have not been able to solve this problem.Can you help ?

this is the error I got at the terminal

./src/App.css (./node_modules/react-scripts/node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/App.css)Module not found: You attempted to import ../public/images/img-8.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
  • Node Version : v12.18.3
  • Npm Version : 6.14.8

My File Structure

- node_modules
 - public
     * images
          * img-2.jpg
     * videos

 - src
    * App.js
    * App.css
    * index.js
    * setupTest.js

the picture i am trying to import in my css file

background-image: url('/public/images/img-2.jpg');

App.js

import React from "react";
import "./App.css";
import Navbar from "./components/Navbar";
import { BrowserRouter as Router,Switch, Route } from "react-router-dom";

function App() {

  return (
   <Router>
     <Navbar></Navbar>
     <Switch>
       <Route path="/" exact />
     </Switch>
   </Router>
  );
}

export default App;

package.json

 {
      "name": "react-website",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@testing-library/jest-dom": "^5.11.6",
        "@testing-library/react": "^11.2.2",
        "@testing-library/user-event": "^12.2.2",
        "css-loader": "^5.0.1",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-router-dom": "^5.2.0",
        "react-scripts": "4.0.1",
        "style-loader": "^2.0.0"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": [
          "react-app",
          "react-app/jest"
        ]
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }
İbrahim
  • 185
  • 1
  • 4
  • 9

1 Answers1

10

You should use /images/img-2.jpg/ to refer to the folder. The reason is that you are using create-react-app to create this React app. When being bundled the app will be located in the public folder. Read this other question where it mentions the same issue.

kunquan
  • 1,127
  • 1
  • 10
  • 24