简体   繁体   English

反应并要求:错误:找不到模块“。”

[英]React & require: Error: Cannot find module “.”

I have a fairly simple stateless component 我有一个相当简单的无状态组件

const Image = ({
    uri,
}) => {
    function getImage(uri) {
        return require(uri);
    }

    return (
        <img
            className='image'
            src={getImage(uri)} />
    )
}

export default Image;

That gives me 那给我

Error: Cannot find module "." 错误:找不到模块“。” webpackMissingModule webpack缺少模块

The image is in the assets folder of my app. 该图像位于我的应用程序的assets文件夹中。

I also tried 我也试过

<img
    lassName='image'
    src={require(uri)} />

The path looks like '../../assets/someImage.jpg' 路径看起来像'../../assets/someImage.jpg'

Why cant I use require with a variable name? 为什么我不能在变量名中使用require When I hardcode the path it works... The path I am giving cannot be wrong because if using the wrong path I would get something like 当我对路径进行硬编码时,...给出的路径不会错,因为如果使用错误的路径,我会得到类似

... not found: Can't resolve .... ...未找到:无法解决....

The problem is require() itself. 问题是require()本身。 require() get's fired, when the app starts. 应用启动时会触发require()被触发。 When a path is passed statically, require() knows where to look when the app starts and all is good. 当静态传递路径时, require()知道应用程序启动时在哪里寻找,一切都很好。 However, when the path gets passed dynamically, require() does not know on start up of the app where to look for the image. 但是,当路径动态传递时, require()在应用程序启动时并不知道在哪里寻找图像。 Hence, it does not find it. 因此,它找不到它。 That is why requiere() cannot take a dynamically created path. 这就是为什么requiere()无法采用动态创建的路径的原因。

Use src='' relative from your index.html or your public folder (depends on your configuration). 使用src=''从你亲戚index.html或您的public文件夹(取决于您的配置)。

Two things I noticed in your code. 我在您的代码中注意到了两件事。

When you want to add css styles to jsx elements you need to use className but lassName. 当您要向jsx元素添加CSS样式时,需要使用className而不是lassName。 Not sure if it is a typo error :) 不知道这是否是拼写错误:)

When you want to import images and add the path to src. 当您要导入图像并将路径添加到src时。

Do some thing like below and make sure your image path is correct. 执行以下操作,并确保您的图像路径正确。

import uri from '../../assets/someImage.jpg';
<img
className='image'
src={uri} />

if its a url 如果是网址

 <img src={'https://cdn-images-1.medium.com/max/1600/1*DsD06sTC-X5AVj_m9nElRg.jpeg'}></img>

or you can store the url in a variable and use in the src like 或者您可以将网址存储在变量中,并在src中使用,例如

var url = 'https://cdn-images-1.medium.com/max/1600/1*DsD06sTC-X5AVj_m9nElRg.jpeg';
        <img src={url}></img>

if its a file inside the src folder 如果它是src文件夹中的文件

<img src={require('./logo.svg')}></img> 

in your case- Solution 在您的情况下-解决方案

 getImage = (url) => {
     return require(`${url}`)
   }

  <img src={this.getImage(url)}></img>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM