html-webpack-plugin

147 阅读2分钟

学习npm包请一定先去npm官方看一下文档介绍,实在不行再去看别人的解说,自己能搞懂是最好的。

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

module.exports = {
  mode:"development",
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module:{
      noParse: /jquery|lodash/,
      //noParse: (content) => /jquery|lodash/.test(content),
      unsafeCache:true, // webpack4 默认为true
      rules:[
          {
              test:/\.css$/,
              use:[
                  'style-loader',
                  'css-loader'
              ]
          },
          {
              test:/\.(png|svg|jpg|gif)$/,
              use:[
                  {
                    loader:'file-loader',
                    options:{
                        outputPath:'/images',
                    }
                  }
              ]
          },
          {
              test:/\.(woff|woff2|eot|ttf|otf)$/,            
              use:[
                  {
                    loader:'file-loader',
                    options:{
                        outputPath:'/font',
                    }
                }
              ]
          },
          {
              test:/\.xml$/,
              use:[
                  'xml-loader'
              ]
          }
      ],
  },
  plugins:[
    new HtmlWebpackPlugin({
        template:'./src/index.html'
    }),
  ]
};

简单来说html-webpack-plugin就是生成一个html文件,可以是无配置的,无配置的情况它可以自动生成一个html,内容如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Webpack App</title>
  </head>
  <body>
    <script src="index_bundle.js"></script> 
  </body>
</html>

<script src="bundle.js"></script> 是把默认bundle.js引入的,但是很多情况下我们的index.html可能有一些特殊的内容,这样默认的配置不能满足,这时候html-webpack-plugin的配置项就会起作用,最经常使用的就是 template:'你的html的路径'.

另一个经常出现的问题的 title:'titleName' 明明配置了,但是生成的html里title却不会改变,认真看官方文档,依据template的html文件里<title><%= htmlWebpackPlugin.options.title %></title> 这样写才可以,其实很多问题看官方说明足以解决了,我们要找到学习的方法。

另外一个经常使用的plugin是clean-webpack-plugin,它的作用是每次build时把 output.path 文件夹下的内容清除掉。

npm install --save-dev clean-webpack-plugin 简写:npm install -D clean-webpack-plugin

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpackConfig = {
    plugins: [
        new CleanWebpackPlugin(),
    ],
};
module.exports = webpackConfig;

最后多说一些 : -S 生产 -D 是开发 一个包是装开发还是生产要看最终上生产时是否会用到包的内容,以react项目举个例子:

react,react-dom包肯定是生产用,如果用了antd那也装生产-S;而eslint,babel,各种loader,各种plugins基本都是build时发挥作用,生成最终文件时就不需要它们了,所以装-D .

如果你不是要开发一个npm包给别人用,其实都装-S就行,webpack不会把这些loader,plugins打进生产文件,除非你要开发一个类似antd的npm包给大家用,这时候你才需要分清开发时依赖还是生产时依赖,不然别人用你的包会多下载一些不必要的包。