首页 > 解决方案 > 如何从 JS 中引用这个外部图像资源?

问题描述

我有一个使用 webpack 和 sass 的 React 应用程序。我远不是这些技术的专家。该应用程序index.scss在顶级 html 元素上使用背景图像,如下所示:

html {
    ...
    background-image: url('./path/to/image/file.jpg');
    ...
}

使用浏览器的开发工具,我可以看到 webpack 已经移动并重命名了图像文件:

background-image: url(http://localhost:6006/c165f4b41cec0.jpg)

现在我想在一些使用React 内联样式的 JS 中引用相同的图像资源:

const SomeComponent = ()=> (
  <div
    style={{
      ...
      backgroundImage: ??? what goes here ???
      ...
    }}
  >
    Some text here...
  </div>
);

无论 webpack 用它做什么,我怎样才能从 JS 中可靠地引用相同的图像资源?

我可以将内联样式转移到另一个 scss 文件中,但我不想这样做,因为我想保持这个特定的 JS 文件自包含。

谢谢。

标签: webpacksassinline-styles

解决方案


我解决了,所以我只是在回答我自己的问题……哎呀。

import jpgFile from './path/to/image/file.jpg'; // <-- add this import

const SomeComponent = ()=> (
  <div
    style={{
      ...
      backgroundImage: 'url(' + jpgFile + ')', // or `url(${jpgFile})`
      ...
    }}
  >
    Some text here...
  </div>
);

推荐阅读