【问题标题】:React CRA - Images EcosystemReact CRA - 图像生态系统
【发布时间】:2018-07-14 04:28:53
【问题描述】:

使用 create-react-app 时,我的 images 文件夹应该在哪个目录下?

srcpublic

当我准备好运行yarn build 时,其中一个会出现问题吗?

我听说只有放在public 目录中的文件会在构建后加载。 对还是错

我猜 React 团队在 index.html 上的这条评论让我感到困惑。

    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
        <!--
          Notice the use of %PUBLIC_URL% in the tags above.
          It will be replaced with the URL of the `public` folder 
          during the build.
          Only files inside the `public` folder can be referenced from 
          the HTML.
          Unlike "/favicon.ico" or "favicon.ico", 
          "%PUBLIC_URL%/favicon.ico" will
         work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->

编辑: 阅读下面的 cmets 后,这就是我在 src 文件夹中的图像文件夹的结构。 你能告诉我这是否是一个好的/最佳实践吗?

**Images Component**
import Foo from "./images/foo.jpg";
import Bar from "./images/bar.jpg";
import './styles/Images.css';

export const Logo = () => (
    <img src={Foo} alt="bla bla" />
)
export const Profile = () => (
    <img src={Bar} alt="bla bla" />
)

我想使用图像的组件。

import { Logo, Profile } from './Images';

const Home = () => (
   <div>
    <Logo/>
    <Profile/>
   </div>
)

【问题讨论】:

    标签: javascript reactjs npm create-react-app yarnpkg


    【解决方案1】:

    您应该在 src 下为图像创建一个文件夹。然后只需使用 import './myImage.png' as imageThatIsMine 将它们导入到 .js 文件中。

    在 .css 中你会使用

    .myClass {
      background-image: url('./myImage.png')
    }
    

    这样做将确保 webpack 正确地将文件移动到构建文件夹并附加正确的路径。

    请参阅docs 了解更多信息。

    如果您将任何内容放在 src 文件夹之外并尝试导入,则会收到一条错误消息,告诉您使用 src。

    您可以将项目放在“公共”文件夹中,但不建议这样做。见docs

    如果您确实使用公用文件夹,则需要在使用它们时加上 %PUBLIC_URL% 前缀。

    【讨论】:

    • 谢谢!你能看到我对这个问题的编辑并告诉我我是否走在正确的轨道上吗?
    • 您的更改会起作用,但大多数人只是将图像导入到使用它的组件中。不需要为每个图像创建单独的组件,除非这是您想要的。
    • 我的目的是让所有应用程序图像都保存在一个文件中,以便于访问和修改。
    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2019-01-26
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多