React, Sass, getting an error when importing img f

2019-02-28 16:34发布

问题:

I want to set a simple background image with an overlay to a react component from a sass file, but I am getting this error, Module not found: You attempted to import ../assets/hero.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported., this is very strange as the assets folder that contains the image is actually inside the /src folder, here is my folder structure

src/ 
  |assets/
          hero.jpg
  |sass/
        |main.scss
        |sassFiles/
                  |components.scss
                  |..
  |components/
             |Navbar.js
             |Home.js
             |..
  |App.js
  |index.js
  |..
             
         
  
/* _components.scss file */

.hero {
  height: 60vh;
  background: linear-gradient(rgba(238, 238, 238, 0.459)), url(../../assets/hero.jpg) no-repeat 50% 50%;
  background-size: cover;
}

when I import the image from the component like so import hero from '../assets/hero.jpg', it works fine, the error occurs only when I import it from the .scss file, other than that, styles are being applied with no problems.

回答1:

What error are you seeing in the web inspector? Trying changing the relative path to your image from:

url(../../assets/hero.jpg)

To:

url(../assets/hero.jpg)


标签: reactjs sass