首页 文章

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

提问于
浏览
7

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

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

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

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

我怎样才能触发webpack动态替换这些相对路径,以及我在webpack配置中配置的内容?

4 回答

  • 9

    我不是webpack专家,但我通过这样做得到了它

    <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加载器就会启动 .

    <%= %> 表示lodash模板

    在引擎盖下,它使用webpack子编译,它继承了主配置中的所有加载器 .

    在img路径上调用 require 然后将调用文件加载器 .

    你可能遇到一些路径问题,但它应该工作 .

  • 0

    使用HTML webpack插件的html-loader为我工作 .

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

    你可以在你的webpack配置中使用url-loader来添加低于特定限制的图像,这些限制在你的最终包中被编码为base64 uri,而在极限之上的图像被添加为常规图像标签(相对于publicPath)

    module.rules.push({
      test: /\.(png|jp(e*)g|gif)$/,
      exclude: /node_modules/,
      use: [{ 
        loader: 'url-loader',
        options: {
          limit: 10000,
          publicPath: "/"
        }
      }]
    })
    
  • 0

    你应该使用 CopyWebpackPlugin .

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

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

    这是 src/assets/images 复制到你的'distfolder / images' .

相关问题