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

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


当前回答

为别人的答案提供更多的信息。关于如何将.png文件交付给用户,您有两个选项。文件结构应该与您选择的方法一致。这两个选项是:

使用react-create-app提供的模块系统(import x from y),并将其捆绑到你的JS中。将图像放在src文件夹中。 从公用文件夹提供该文件,并让Node提供该文件。Create-react-app显然还附带了一个环境变量,例如<img src={process.env。PUBLIC_URL + '/img/logo.png'} />;。这意味着你可以在你的React应用中引用它,但仍然可以通过Node提供服务,你的浏览器会在一个正常的GET请求中单独请求它。

来源:create-react-app

其他回答

我能够导入文件src/外部的“复制”文件与file:作为本地依赖。

"dependencies": {
    "@my-project/outside-dist": "file:./../../../../dist".
}

then

import {FooComponent} from "@my-project/outside-dist/components";

不需要弹出或react-app-rewired或其他第三方解决方案。

此限制确保所有文件或模块(导出)都在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:注意弹出的后果。

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

下面是一个在简单情况下工作得很好的替代方案(使用fs和ncp)。在开发过程中,保持一个脚本运行,以监视/src之外的共享文件夹的更改。当进行更改时,脚本可以自动将共享文件夹复制到项目中。下面是递归地查看单个目录的示例:


// This should be run from the root of your project

const fs = require('fs')
const ncp = require('ncp').ncp;

ncp.limit = 16

// Watch for file changes to your shared directory outside of /src
fs.watch('../shared', { recursive: true }, (eventType, filename) => {
    console.log(`${eventType}: ${filename}`)

    // Copy the shared folder straight to your project /src
    // You could be smarter here and only copy the changed file
    ncp('../shared', './src/shared', function(err) {
        if (err) {
          return console.error(err);
        }

        console.log('finished syncing!');
    });
})

有一些答案提供了react-app-rewired的解决方案,但customize-cra包括一个removeModuleScopePlugin() API,它更优雅一些。(这是相同的解决方案,但被customize-cra包抽象了。)

NPM I——save-dev react-app-rewired customize-cra

package.json

"scripts": {
    - "start": "react-scripts start"
    + "start": "react-app-rewired start",
    ...
},

config-overrides.js

const { removeModuleScopePlugin } = require('customize-cra')

module.exports = removeModuleScopePlugin()