Index.html模板未为HtmlWebpackPlugin加载网站图标

时间:2018-08-26 08:18:05

标签: javascript node.js webpack webpack-dev-server

我正在尝试使用favicon的模板模板index.html加载HtmlWebpackPlugin,但没有加载。

这就是我的Webpack配置的样子:

'use strict'

const webpack = require('webpack')
const { join, resolve } = require('path')

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: join(__dirname, 'src', 'index'),
  output: {
    filename: 'bundle.js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.s?css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      }
    ]
  },
  resolve: {
    extensions: ['.js']
  },
  devServer: {
    contentBase: resolve(__dirname, 'build')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: join(__dirname, 'public', 'index.html')
    })
  ]
}

这就是我的index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="shortcut icon" href="favicon.ico">

  <title>React App</title>
</head>

<body>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>

  <div id="root"></div>
</body>

</html>

2 个答案:

答案 0 :(得分:1)

HTMLWebpackPlugin不会解析HTML来查找您的资源。您需要在模板中包含以下内容:

index.html

<link rel="shortcut icon" href="${require('favicon.ico')}">

您还需要为file-loader文件添加.ico

webpack.config.js

{
   test: /\.ico$/,
   loader: 'file-loader'
}

答案 1 :(得分:1)

HtmlWebpackPlugin 有一个名为 favicon 的选项,可让您在开发或生产中将图标链接注入到标题中。

        new HtmlWebpackPlugin({
            title: "Title Here",
            template: "./src/index.html",
            favicon: "./src/favicon.ico",
            inject: "body",
        })

您还应该有一个 rule 来抓取图标,并将其导入到您的打包程序文件中。

            // # Target: favicon
            {
                test: /\.ico$/i,
                type: "asset/resource",
                // Use 'generator' to output unique name (based on webpack pattern e.g. [name], [ext], etc.)
                generator: {
                    filename: "[name][ext][query]"
                }
            },

注意:我正在为 Webpack 5 编写

我不确定 Webpack 4 是否具有 type: "asset/resource" 功能,但我认为您可以使用 file-loader 及其选项实现相同的功能。

            {
                test: /\.ico$/i,
                use: {
                    loader: "file-loader",
                    options: {
                        name: "[name].[ext]"
                    }
                }
            },

*不保证适用于 Webpack 4