简体   繁体   中英

Using images directly in html tags by webpack

I'm novice to webpack and I was wondering is it possible to use images directly in html tags? I was able to load images in CSS file as background :

background: url("../images/dog.png")

But when I want to use it in img tag like this:

<img id="home" height='75px' width='75px' src="../src/images/dog.png" /> 

I got error: Cannot GET /src/images/dog.png This is my webpack.config:

            {
            test: /\.(gif|png|jpeg?g|svg)/i,
            use: [{
                loader: 'url-loader',
                options: { 
                    name: 'images/[name].[ext]',
                    gifsicle:{
                        interlanced: false
                    },
                    optipng:{
                        optimizationLevel: 7
                    },
                    pngquant: {
                        quality: "65-90",
                        speed: 4
                    },
                    mozjpg:{
                        progressive: true,
                        quality: 65
                    }
                } 
            }]
        }

And the hierarchy of my project:

在此处输入图片说明

Whats going wrong?

Under your public folder create an images folder and in your html img tag just pass the path of your images folder:

<img id="home" height='75px' width='75px' src="/images/dog.png" />

if you want to use the image inside your js file or jsx use webpack import

import React from 'react
import dog from './src/images/dog.png'

// ReactJS like component and images imports.
const RenderDogImage = (props) => <img src={dog} alt='This is a dog' />

sand box without react: https://codesandbox.io/s/k08zx1xv03

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