简体   繁体   English

webpack4 react jsx 无法渲染 img

[英]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编译的 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?为什么 create-react-app 可以使用第二种方式?

I hope that the image can be rendered in the second way.我希望图像可以以第二种方式呈现。

my webpack.base.config url-loader我的 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删除 webpack 配置中名称的哈希值

{
  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. Create-react-app 也不起作用。

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

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