我正在使用create-react-app。我试图从我的src/components内部的文件中调用我的公共文件夹中的图像。我收到这个错误信息。

./src/components/website_index.js模块未找到:你试图 import ../../public/images/logo/WC-BlackonWhite.jpg 在项目src/目录之外。国外的相对进口 Src /不支持。您可以将它移动到src/,或者添加一个 从项目的node_modules/到它的符号链接。

从“../../public/images/logo_2016.png”导入logo; <img className="Header-logo" src={logo} alt=" logo" />

我读过很多东西,说你可以做一个导入的路径,但这仍然不是为我工作。任何帮助都将不胜感激。我知道有很多这样的问题,但他们都告诉我导入标志或形象,所以很明显,我在大局中遗漏了一些东西。


当前回答

在制作《Truffle》时,我不得不克服同样的问题。解决方案如下:

由于Create-React-App的默认行为不允许从src文件夹外导入文件,我们需要将build文件夹中的合同带到src内。我们可以在每次编译合同时复制并粘贴它们,但更好的方法是简单地配置Truffle将文件放在那里。

在“truffle-config.js”文件中,替换如下内容:

const path = require("path");

module.exports = {
  contracts_build_directory: path.join(__dirname, "client/src/contracts")
};

我不知道这是否对你有帮助,但我知道当我在Truffle中遇到同样的问题时,我发现了你的问题,这可能会帮助其他人。

其他回答

你需要移动WC-BlackonWhite.jpg到你的src目录。public目录是用于直接链接到HTML中的静态文件(如favicon),而不是用于直接导入到bundle中的内容。

您不需要弹出,您可以使用rescripts库修改react-scripts配置

这样就可以了:

module.exports = config => {
  const scopePluginIndex = config.resolve.plugins.findIndex(
    ({ constructor }) => constructor && constructor.name === "ModuleScopePlugin"
  );

  config.resolve.plugins.splice(scopePluginIndex, 1);

  return config;
};

这可以直接完成,而无需使用公共文件夹的路径。 你可以这样做

<img src="/images/image-name" alt=""/>

这是因为我们没有在浏览器中使用App.js。由于index.html是在浏览器本身执行的,图像的路径已经在包含index.html文件的公共文件夹中

如果你想使用CSS设置背景图像。因此,您必须使用本地主机的URL设置图像并添加图像的路径。请看下面的例子。

.banner {
  width: 100%;
  height: 100vh;
  background-image: url("http://localhost:3000/img/bg.jpg");
  background-size: cover;
  background-repeat: no-repeat;
}

用Craco去除:

module.exports = {
  webpack: {
    configure: webpackConfig => {
      const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
        ({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
      );

      webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
      return webpackConfig;
    }
  }
};