Webpack —— 前端工程化(构建篇)

320 阅读2分钟

Webpack一直是前端开发不能缺少的重要工具,当中很多常用的组件配置,往往都没有一个全局的认识和系统的学习,这篇文章旨在记录webpack中一些常用的插件、配置、优化方案,作一个基础的总结。

关于脚手架

插件

html-webpack-plugin

描述:模版处理插件,协助将打包压缩的文件名、路径插入模版当中

原理:将webapckentry配置的chunk或抽取的公共样式,插入到提供的template模版中,生成一个html文件;将样式的link插入head标签中,script插入headbody中。

常用参数与使用示例

import HtmlWebpackPlugin from 'html-webpack-plugin'

const config = {
  ...otherConfig,
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'index.html'), // 本地模版文件地址,会接受模版loader解析,默认为ejs-loader 
      filename: 'index.html', // 相对output.path输出文件名或路径,可以指定输出目录
      templateContent: '<html></html>', // 不与template共存,可为function,返回html字符串
      inject: true, // 为false不注入静态文件,为head将js注入head,为true或body将js注入body底部
      chunks: 'all', // 方便多个模版时,注入不同的chunk,字符串数组
      excludeChunks: '', // 排除注入的chunk
      showErrors: true, // 默认true,将错误信息输出到页面中
      minify: html-minifier插件配置,压缩html文件
      xhtml: true, // 渲染的标签自闭合
      ['custom_params']: 'xxx', // 可以自定义参数名称,都可以在模版内使用模版语法访问到
    }),
    new HtmlWebpackPlugin({}) // 多个模版直接写多个plugin就行
  ]
}

有了这些配置参数,足以常规的配置选项了,接下来再看下我们对应的模版内需要如何使用HtmlWebpackPlugin的自定义参数。

<!DOCTYPE html>
<html style="font-size:20px">
<head>
    <meta charset="utf-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <% for (var css in htmlWebpackPlugin.files.css) { %>
    <link href="<%=htmlWebpackPlugin.files.css[css] %>" rel="stylesheet">
    <% } %>
</head>
<body>
<div id="app">这里面没啥好看的,看下面的参数介绍</div>
<% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
<script type="text/javascript" src="<%=htmlWebpackPlugin.files.chunks[chunk].entry %>"></script>
<% } %>
</body>
</html>

模版文件内可以看出来,我们整体使用的是一个htmlWebpackPlugin参数,通过这个参数可以访问模版编译时的webpack对象,也可以访问options内,我们自定义的参数。那这个对象具体有哪些可访问参数,可以看看下面这个参数示意。

var templateParams = {
    compilation: compilation, // 编译对象
    webpack: compilation.getStats().toJson(), // stats
    webpackConfig: compilation.options, // webpack配置,如:webpackConfig.output.publicPath
    htmlWebpackPlugin: {
      files: { // 配置的chunk与抽取的css样式
        css: ['index.css'],
        js: ['common.js', 'index.js'],
        chunks: {
          common: {
            entry: 'common.js',
            css: ['index.css'],
          },
          index: {
            entry: 'index.js',
            css: ['index.css']
          }
        }
      },
      options: self.options // 传递给插件的自定义参数,如:title
    }
}

除了这些,这个插件提供了一系列的生命周期事件,供其他插件访问,这里就不做扩展了。