我正在使用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" />

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


当前回答

此限制确保所有文件或模块(导出)都在src/目录中,实现在./node_modules/react-dev-utils/ModuleScopePlugin.js中,在以下代码行中。

// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
     const relative = path.relative(appSrc, request.context.issuer);
// If it's not in src/ or a subdirectory, not our request!
     if (relative.startsWith('../') || relative.startsWith('..\\')) {
        return callback();
      }

您可以通过

修改这段代码(不推荐) 或者执行eject,然后从目录中删除ModuleScopePlugin.js。 const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');从。/ node_modules / react-scripts / config / webpack.config.dev.js

PS:注意弹出的后果。

其他回答

我认为Lukas Bach的解决方案使用react-app-rewired来修改webpack配置是一个很好的方法,但是,我不会排除整个ModuleScopePlugin,而是将可以从src导入的特定文件列入白名单:

config-overrides.js

const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");

module.exports = function override(config) {
  config.resolve.plugins.forEach(plugin => {
    if (plugin instanceof ModuleScopePlugin) {
      plugin.allowedFiles.add(path.resolve("./config.json"));
    }
  });

  return config;
};

如果你想从公共目录访问CSS文件,你可能会遇到OUTSIDE OF SOURCE DIRECTORY错误

或者,您可以在index.html中链接此文件,该文件也位于公共目录中。

<link rel="stylesheet" href="App.css">

您不需要弹出,您可以使用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;
};

最好的解决方案是fork react-scripts,这实际上在官方文档中提到过,参见:ejection的替代方案

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

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

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