简体   繁体   中英

webpack4 react jsx can't render img

import React from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import icon from '@/assets/images/bg.jpg'

const App = () => {
  return (
    <Router>
      <div>
        <img src={icon} alt="logo" /> {/* success */}
        <img src="./assets/images/bg.jpg" alt="logo" /> {/* fail */}
      </div>
    </Router>
  )
}

export default App;

Compiled HTML

<div>
<img src="/img/bg.896ed149.jpg" alt="logo">
<img src="./assets/images/bg.jpg" alt="logo">
</div>

Why can create-react-app use the second way?

I hope that the image can be rendered in the second way.

my webpack.base.config url-loader

{
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  loader: 'url-loader',
  options: {
    limit: 8192,
    name: 'img/[name].[hash:8].[ext]'
  }
},

The image is copied in your build folder but the name did not match. Remove the hash for the name in your webpack config

{
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  loader: 'url-loader',
  options: {
    limit: 8192,
    name: 'img/[name].[ext]'
  }
},

Another thing is you should change the image url like this

 <img src='/img/bg.jpg'/>

Sorry, I got it wrong. Create-react-app don't work either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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