使用HTMLWebpackPlugin时如何通过webpack加载图像?

vxbzzdmp  于 2024-01-08  发布在  Webpack
关注(0)|答案(5)|浏览(128)

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

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

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

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


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

enxuqcxy

enxuqcxy1#

我不是一个webpackMaven,但我通过这样做让它工作:

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

字符串
插件配置

  1. new HtmlWebpackPlugin({
  2. filename: 'index.html',
  3. template: 'index.html'
  4. }),


根据文档:https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md
默认情况下(如果您没有以任何方式指定任何加载器),会启动一个回退lodash加载器。
<%= %>表示lodash模板
在引擎盖下,它使用了一个webpack子编译,它继承了主配置中的所有加载器。
在img路径上调用require将调用文件加载器。
您可能会遇到一些路径问题,但它应该可以工作。

展开查看全部
carvr3hs

carvr3hs2#

使用HTML加载器与HTML webpack插件为我工作。

  1. module: {
  2. rules: [
  3. {
  4. test: /\.(html)$/,
  5. use: ['html-loader']
  6. }
  7. ]
  8. },
  9. plugins: [
  10. new HtmlWebpackPlugin({
  11. template: './src/index.html'
  12. })
  13. ]

字符串

oprakyz7

oprakyz73#

你应该使用CopyWebpackPlugin
const CopyWebpackPlugin = require('copy-webpack-plugin');

  1. plugins:[
  2. ....
  3. new CopyWebpackPlugin({'patterns': [
  4. { from: './src/assets/images', to: 'images' }
  5. ]}),
  6. ....
  7. ]

字符串
这是将src/assets/images复制到dist/folder/images

pcrecxhr

pcrecxhr4#

你可以在你的webpack配置中使用url-loader来在你的最终包中添加低于某个限制的图片,这些图片被编码为base64 uri,而超过限制的图片则作为常规图片标签(相对于publicPath)。

  1. module.rules.push({
  2. test: /\.(png|jp(e*)g|gif)$/,
  3. exclude: /node_modules/,
  4. use: [{
  5. loader: 'url-loader',
  6. options: {
  7. limit: 10000,
  8. publicPath: "/"
  9. }
  10. }]
  11. })

字符串

yhived7q

yhived7q5#

我在遵循Webpack提供的入门指南时遇到了这个问题。我使用的是指南中的模板代码和捆绑图像。但是当迁移现有的vanilla html/js/css项目使用Webpack时,我发现,为了像我想要的那样使用模板HTML加载-模板中包含图像资源的路径-我必须从webpack.config.js中删除资产加载器的使用,以便html-loader正确解析它在dist中创建的新散列路径
要使用Webpack文档语法,请删除前缀为“-”的行,并添加前缀为“+”的行

  1. module: {
  2. rules: [
  3. {
  4. - test: /\.(png|svg|jpg|jpeg|gif)$/i,
  5. - type: 'asset/resource',
  6. + test: /\.(html)$/,
  7. + use: ['html-loader'],
  8. }
  9. ]
  10. }

字符串

相关问题