简体   繁体   English

无法理解背景图像 url 如何在 Gatsby.js 中工作

[英]Cannot understand how background-image url works in Gatsby.js

I am learning Gatsby.我正在学习盖茨比。 I have a component called Hero which is for displaying a banner for the blog I am building.我有一个名为Hero的组件,用于为我正在构建的博客显示横幅。

import React from 'react';
import styled from '@emotion/styled';
import { Link, graphql, useStaticQuery } from 'gatsby';

const ImageBackground = styled('div')`
  background-image: url('images/plans-background.jpg'); <--- this url doesn't make sense to me
  background-position: top 20% center;
  background-size: cover;
  /* background-color: red; */
`;

const Hero = () => {
  return (
    <ImageBackground>
      <h1>Frontend Masster dsfsdfsd</h1>
      <p>
        hello
        <Link to="/about">learn about me</Link>
      </p>
    </ImageBackground>
  );
};

export default Hero;

I'm using the screenshot to show the folder structure我正在使用屏幕截图来显示文件夹结构在此处输入图像描述

according to the structure, in order to reach the background image I need a url like this根据结构,为了达到背景图像,我需要这样的 url

`../../../static/images/plans-background.jpg`

And that's what the IDE prompted me to type when trying to reach the image file.这就是 IDE 在尝试访问图像文件时提示我输入的内容。 However this url doesn't work as expected.但是,此 url 无法按预期工作。 There's no background image showing.没有显示背景图像。 and I changed it to我把它改成了

`images/plans-background.jpg`

The background image showed up magically.背景图像神奇地出现了。

So I don't understand why this url is working.所以我不明白为什么这个 url 工作。 Is it something special about the folder static or is Gatsby doing something behind the scene?文件夹static有什么特别之处,还是盖茨比在幕后做了什么?

Also when I opened up the devtool to inspect the resources that got loaded, I didn't find this static file, neither the background image file.此外,当我打开 devtool 检查加载的资源时,我没有找到这个static文件,也没有找到背景图像文件。

I am really trying to understand how these pieces work together我真的很想了解这些部分是如何协同工作的在此处输入图像描述

Yes, this is the expected behavior for your assets in /static , read more about it in the docs: Using the Static Folder .是的,这是/static中资产的预期行为,请在文档中了解更多信息:使用 Static 文件夹

However, adding your images there is not a best practice because they won't be optimized with Gatsby's build time image processing and gatsby-image .但是,在此处添加图像并不是最佳实践,因为它们不会使用 Gatsby 的构建时图像处理和gatsby-image进行优化。

The docs also have good resources for this: Using Gatsby Image to Prevent Image Bloat , or Working with images in Gatsby .文档也有很好的资源: Using Gatsby Image to prevent Image Bloat ,或者Working with images in Gatsby

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM