使用HTMLWebpackPlugin时如何通过webpack加载图像? [英] How to load images through webpack when using HTMLWebpackPlugin?

查看:102
本文介绍了使用HTMLWebpackPlugin时如何通过webpack加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTMLWebpackPlugin,在我的模板中我有一个img标签:

I am using HTMLWebpackPlugin and in my template I have an img tag:

<img src="./images/logo/png">

如果你注意到,这里我使用的是相对路径,认为webpack会触发配置的文件加载器我的webpack.config.js文件,但在编译后,我在我的html中得到完全相同的src属性:

If you notice, here I am using a relative path thinking webpack will trigger the file loader that's configured in my webpack.config.js file but after compilation I get the exact same src attribute in my html:

<img src="./images/logo/png">

如何触发webpack动态替换这些相对路径,以及我在我配置的任何内容webpack配置?

How can I trigger webpack to dynamically replace these relative paths with, well whatever I've configured in my webpack configuration?

推荐答案

我不是网络专家,但我通过这样做得到它

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

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

插件配置

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

根据文档: https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md


默认情况下(如果你没有以任何方式指定任何加载器),后备
lodash加载器就会启动。

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

<%=%> 表示lodash模板

The <%= %> signifies a lodash template


它使用了一个webpack子编译,它从你的主配置继承
所有加载器。

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

在你的img路径上调用 require 然后调用文件加载器。

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

你可以遇到一些路径问题,但是它应该工作。

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

这篇关于使用HTMLWebpackPlugin时如何通过webpack加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆