webpack(8)_html_使用html-webpack-plugin

版权声明:本博客主要记录学习笔记和遇到的一些问题解决方案,转载请注明出处! https://blog.csdn.net/u010982507/article/details/82049094

本章主要记录讲述如何使用html-webpack-plugin来生成html。主要记录以下三点:

  • html-webpack-plugin的使用
  • 使用html-loader处理html中引入的图片
  • 处理html中图片和css中的图片

- 使用html-webpack-inline-chunk-plugin优化

html-webpack-plugin的使用

  • 安装
npm install html-webpack-plugin --save-dev
  • 引入
var HtmlWebpackPlugin = require('html-webpack-plugin');
  • 在plugin中配置
plugins: [
  new HtmlWebpackPlugin({
      filename: 'index.html', // 默认是index.html
      template: './index.html',
      //inject:false, // 不会将生成的css和js插入到页面中
      chunks: 'index', // 指定chunk后,会将与这个chunk相关的js和css引入到html中,处理多entry文件
      minify: {
          collapseWhitespace: true // 压缩空格
      }
  })
]

使用html-loader处理html中引入的图片

  • 安装html-loader
npm install html-loader --save-dev
  • 在module中的配置
{
    test: /\.html$/,
    use: [
        {
            loader: 'html-loader',
            options: {
                attrs: ['img:src', 'img:data-src'] // 配置处理html中的图片
            }
        }
    ]
}

处理html中图片和css中的图片

  • 使用file-loader和url-loader处理,使用url-loader之前要先安装file-loader
  • 配置url-loader,配置的时候去掉相对路径的使用useRelativePath: true
output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "", // 设为空,引入的css和js之前不会有'/'
    filename: "[name].bundle.js"
},


{
    loader: 'url-loader',
    options: {
        name: '[name].[ext]',// 打包后的文件名称
        outputPath: 'images/', // 默认是dist目录,会在标签或者css前面
        publicPath: 'images', // 图片的url前面追加'dist/images'
        limit: 1000
    }
}

使用html-webpack-inline-chunk-plugin优化

https://www.npmjs.com/package/html-webpack-inline-chunk-plugin

clean-webpack-plugin的使用

  • 作用
    打包时删除指定目录。
  • 安装
    npm install clean-webpack-plugin –save-dev
  • 引入
var CleanWebpackPlugin = require('clean-webpack-plugin');
  • 配置
plugins: [
   new CleanWebpackPlugin(['dist']) // 删除指定目录
]
  • 测试
    执行打包时,会打印日志dist has been removed.

猜你喜欢

转载自blog.csdn.net/u010982507/article/details/82049094