How to load images through webpack when using HTMLWebpackPlugin?

那年仲夏 提交于 2019-12-03 04:53:35

I'm not a webpack expert, but i got it to work by doing this

<img src="<%=require('./src/assets/logo.png')%>">

Plugin config

new HtmlWebpackPlugin({
    filename: 'index.html',
    template: 'index.html'
  }),

According to the docs: https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md

By default (if you don't specify any loader in any way) a fallback lodash loader kicks in.

The <%= %> signifies a lodash template

Under the hood it is using a webpack child compilation which inherits all loaders from your main configuration.

Calling require on your img path will then call the file loader.

You may run into some path issues, but it should work.

Using html-loader with HTML webpack plugin worked for me.

module: {
    rules: [
      {
         test: /\.(html)$/,
         use: ['html-loader']
      }
    ]
},
plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]

You should use the CopyWebpackPlugin.

const CopyWebpackPlugin = require('copy-webpack-plugin');

plugins:[
    ....
    new CopyWebpackPlugin([
         {from:'./src/assets/images',to:'images'} 
     ]),
    ....
]

This is copy the src/assets/images to your `distfolder/images'.

You could use url-loader in your webpack config to add images below a certain limit encoded as base64 uri's in your final bundle and images above the limit as regular image tags (relative to the publicPath)

module.rules.push({
  test: /\.(png|jp(e*)g|gif)$/,
  exclude: /node_modules/,
  use: [{ 
    loader: 'url-loader',
    options: {
      limit: 10000,
      publicPath: "/"
    }
  }]
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!