your programing

React는 로컬 이미지를로드하지 않습니다.

lovepro 2020. 10. 6. 18:51
반응형

React는 로컬 이미지를로드하지 않습니다.


작은 반응 앱을 만들고 있는데 로컬 이미지가로드되지 않습니다. placehold.it/200x200로드와 같은 이미지. 서버에 문제가있을 수 있다고 생각 했나요? github 의 전체 소스 .

여기 내 App.js가 있습니다.

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div className="home-container">
                <div className="home-content">
                    <div className="home-text">
                        <h1>foo</h1>
                    </div>
                    <div className="home-arrow">
                        <p className="arrow-text">
                            Vzdělání
                        </p>
                        <img src={"/images/resto.png"} />
                    </div>
                </div>
            </div>
        );
    }
}

export default App;

index.js :

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';

let history = createHistory();

render(
    <Router history={history} >
        <Route path="/" component={App} >
            <Route path="vzdelani" component="" />
            <Route path="znalosti" component="" />
            <Route path="prace" component="" />
            <Route path="kontakt" component="" />
        </Route>
        <Route path="*" component="" />
    </Router>,
    document.getElementById('app')
);

및 server.js :

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});

Webpack을 사용할 때 Webpack에서 require이미지를 처리하기 위해 이미지 가 필요 합니다. 이는 내부 이미지가로드되지 않는 동안 외부 이미지가로드되는 이유를 설명하므로 대신 image-name.png를 각각의 올바른 이미지 이름으로 대체 <img src={"/images/resto.png"} />해야 <img src={require('/images/image-name.png')} />합니다. 그런 식으로 Webpack은 소스 img를 처리하고 교체 할 수 있습니다.


저는 create-react-app으로 제 앱을 만들기 시작했습니다 ( "새 앱 만들기"탭 참조). 함께 제공되는 README.md는 다음 예제를 제공합니다.

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

이것은 나를 위해 완벽하게 작동했습니다. 다음 은 해당 README에 대한 마스터 문서에 대한 링크입니다 (발췌).

... JavaScript 모듈에서 바로 파일을 가져올 수 있습니다. 이것은 Webpack에 번들에 해당 파일을 포함하도록 지시합니다. CSS 가져 오기와 달리 파일 가져 오기는 문자열 값을 제공합니다. 이 값은 코드에서 참조 할 수있는 최종 경로입니다 (예 : 이미지의 src 속성 또는 PDF 링크의 href).

서버에 대한 요청 수를 줄이기 위해 10,000 바이트 미만의 이미지를 가져 오면 경로 대신 데이터 URI가 반환됩니다. 이는 다음 파일 확장자에 적용됩니다 : bmp, gif, jpg, jpeg 및 png ...


다른 방법 :

먼저 다음 모듈을 설치하십시오. url-loader,file-loader

npm 사용 : npm install --save-dev url-loader file-loader

다음으로 Webpack 구성에 다음을 추가하십시오.

module: {
    loaders: [
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }

limit: 데이터 URL로 인라인 파일에 대한 바이트 제한

You need to install both modules: url-loader and file-loader

Finally, you can do:

<img src={require('./my-path/images/my-image.png')}/>

You can investigate these loaders further here:

url-loader: https://www.npmjs.com/package/url-loader

file-loader: https://www.npmjs.com/package/file-loader


Actually I would like to comment, but I am not authorised yet. That is why that pretend to be next answer while it is not.

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png

function Header() {
// Import result is the URL of your image
  return <img src={logo} alt="Logo" />;

I would like to continue that path. That works smoothly when one has picture one can simple insert. In my case that is slightly more complex: I have to map several pictures it. So far the only workable way to do this I found is as follows

import upperBody from './upperBody.png';
import lowerBody from './lowerBody.png';
import aesthetics from './aesthetics.png';

let obj={upperBody:upperBody, lowerBody:lowerBody, aesthetics:aesthetics, agility:agility, endurance:endurance}

{Object.keys(skills).map((skill) => {
 return ( <img className = 'icon-size' src={obj[skill]}/> 

So, my question is whether are there simplier ways to process these images? Needless to say that in more general case number of files that must be literally imported could be huge and number of keys in object as well. (Object in that code is involved clearly to refer by names -its keys) In my case require-related procedures have not worked - loaders generated errors of strange kind during installation and shown no mark of working; and require by itself has not worked neither.


I too would like to add to the answers from @Hawkeye Parker and @Kiszuriwalilibori:

As was noted from the docs here, it is typically best to import the images as needed.

However, I needed many files to be dynamically loaded, which led me to put the images in the public folder (also stated in the README), because of this recommendation below from the documentation:

Normally we recommend importing stylesheets, images, and fonts from JavaScript. The public folder is useful as a workaround for a number of less common cases:

  • You need a file with a specific name in the build output, such as manifest.webmanifest.
  • You have thousands of images and need to dynamically reference their paths.
  • You want to include a small script like pace.js outside of the bundled code.
  • Some library may be incompatible with Webpack and you have no other option but to include it as a tag.

Hope that helps someone else! Leave me a comment if I need to clear any of that up.


Try changing the code in server.js to -

app.use(require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: config.output.path
    }));

Sometimes you may enter instead of in your image location/src: try

./assets/images/picture.jpg

instead of

../assets/images/picture.jpg

I just wanted to leave the following which enhances the accepted answer above.

In addition to the accepted answer, you can make your own life a bit easier by specifying an alias path in Webpack, so you don't have to worry where the image is located relative to the file you're currently in. Please see example below:

Webpack file:

module.exports = {
  resolve: {
    modules: ['node_modules'],
    alias: {
      public: path.join(__dirname, './public')
    }
  },
}

Use:

<img src={require("public/img/resto.ong")} />

src={"/images/resto.png"}

Using of src attribute in this way means, your image will be loaded from the absolute path "/images/resto.png" for your site. Images directory should be located at the root of your site. Example: http://www.example.com/images/resto.png


The most effective solution that I came across was to set the image using CSS

.profile_img {
   background-image: url('https://img.icons8.com/contacts.png');
}

You can provide your jsx a similar class name

 <Icon className="profile_img" />

In the component declaration you can simply do this

const Icon = () => {
   return(
     <img src='' alt='profileicon'/>
   )
}

What worked for me was to insert the path between backticks and ${}. So for example, instead of:

<img src={require("../images/resto.png")} />

use:

<img src={require(`${../images/resto.png}`} />

This way, when the code is compiled the correct path is inserted.

참고URL : https://stackoverflow.com/questions/34582405/react-wont-load-local-images

반응형