Index.html 模板未加载 HtmlWebpackPlugin 的图标

xah*_*uzu 2 javascript node.js webpack webpack-dev-server

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

这就是我的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')
    })
  ]
}
Run Code Online (Sandbox Code Playgroud)

那是我的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>
Run Code Online (Sandbox Code Playgroud)

Dan*_*rzo 5

HTMLWebpackPlugin 不会解析 HTML 来查找您的资源。您需要在模板中像这样包含它:

索引.html

<link rel="shortcut icon" href="${require('./favicon.ico')}">
Run Code Online (Sandbox Code Playgroud)

您还需要file-loader为您的.ico文件包含:

webpack.config.js

{
   test: /\.ico$/,
   loader: 'file-loader'
}
Run Code Online (Sandbox Code Playgroud)