【问题标题】:display image in html using webpack使用 webpack 在 html 中显示图像
【发布时间】:2022-01-13 03:53:13
【问题描述】:

当我在开发模式下使用 html-loader 和文件加载器时 图片在浏览器中不显示 src->assets->images 文件夹中的图像 并在 html 文件中

请建议我如何在开发和产品模式下运行代码

<html>
    <head>Webpack</head>
    <body>
        <h1>Hi...................!</h1>
        <h1>Owsam!</h1>
        <img src="../src/assets/images/rajstan.jpg">
    </body>
</html>
const road = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    module:{
        rules :[
            {
                test : /\.css$/,
                use  : ['style-loader','css-loader']

            },
            {
                test    :   /\.html$/,
                use     :   [
                    {
                        loader : "html-loader",

                    }
                ]
            },
            {
                test    : /\.(svg|png|jpe?g|gif)$/,
                use     : [
                    {
                        loader : "file-loader",
                        // options : {

                        //     name: '[name].[ext]',
                        //     // outputPath : 'images',
                        //     // publicPath : 'assets'

                        // }  
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            title : 'first webpack',
            filename : 'index.html',
            template : road.resolve(__dirname,'..','public','index.html'),
            inject:'body'
    })]
}

【问题讨论】:

    标签: webpack webpack-dev-server webpack-file-loader webpack-html-loader


    【解决方案1】:

    使用 webpack 4

    module: {
      rules: [
        // other stuff above.....
        {
          test: /\.html$/,
          use: [
            // ...The other file-loader and extract-loader go here.
            {
              loader: 'html-loader'
              options: {
                // THIS will resolve relative URLs to reference from the app/ directory
                root: path.resolve(__dirname, 'app')
              }
            }
          ]
        }
      ]
    }
    

    这告诉html-loader 解释 /app 文件夹中的所有绝对 URL。所以在我们的app/templates/foo.html中,你就可以使用下面的...

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

    然后这告诉html-loader 将上面的内容视为path.resolve(__dirname, 'app', 'images', 'foo.png')。那么如果你有 extract-loader 和/或 file-loader,所有的路径都应该是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-14
      • 2018-06-23
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2021-07-09
      • 2020-11-24
      • 2015-04-15
      相关资源
      最近更新 更多