Create React App 4.0 无法解析公共文件夹中的图像路径

IT技术 reactjs webpack create-react-app
2021-05-24 13:19:14

我已经升级到最新的 Create React App 4.0。现在scss无法解析公共文件夹中的图像资产。我之前使用的是 CRA 3.4.1。它工作得很好。

有任何想法吗?我不想使用npm eject

icon.svg 在 public/images

background-image: url(/images/icon.svg);

Failed to compile.

./src/Components/style.scss 
(./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!
./node_modules/postcss-loader/src??postcss!
./node_modules/resolve-url-loader??ref--5-oneOf-6-3!
./node_modules/sass-loader/dist/cjs.js??ref--5-oneOf-6-4!
./src/Components/style.scss)
Error: Can't resolve '../../../../../../icon.svg' in ''

在 Create React App 3.x 中,从(S)CSS 中公共文件夹引用图像只需使用起始斜杠即可,如已在此处回答

正如 OP 所解释的那样,图像在public/images并被引用为url(/images/icon.svg).

这不再适用于 Create React App 4.0.0 并给出错误消息Error: Can't resolve '../../../../../../icon.svg' in ''Create React App的更新日志没有提到公共文件夹的重大更改。

3个回答

尝试更改为:(webpack 应该将其解析为“真实”路径)

background-image: url(./icon.svg);

我知道您想将图像添加为background-image css 属性,但也许另一种方法与您相关。
当您像这样导入时,您可以像使用普通组件一样使用它:

import { ReactComponent as Icon } from'<path_to_resource>/images/icon.svg';

<Icon />

来源:https : //create-react-app.dev/docs/adding-images-fonts-and-files/

我认为它已被弃用CRA 4,(毕竟......这是一个重大变化......)有一些解决方法正在使用,craco但我建议将这些文件移动到src文件夹中。

作为临时解决方法,您可以将图像移动到 中src/,直接在组件中导入它们import myImage from '../file.svg'并设置style={{ backgroundImage: file }}>?