webpack 打包过程及常用插件

前言

  要理解webpack 首先明白三个概念:module,chunk,bundles,即输入,中间态,输出。

  chunk: This webpack-specific term is uesd internallt to manage the bunding process. Bundles are composed out of chunks,of which there of several tyeps (entry and child). Typically ,chunks correspond with the output bundles,however,there are some configurations that don't yield a one-to-one relationship. Simply,a chunk is a group of modules within the webpack process , a bundle is an emitted chunks or a set of chunks.

主要内容

  webpack 就是 loader 与 plugin 的集合,loader 用于加载不同的文件,plugin 用于优化打包过程。

  webpack 的主要构建流程如下:

  (1)解析webpack 配置参数,合并从命令行输入的参数和 webpack.config.js配置文件的配置参数,生成最终的配置结果。

  (2)注册在配置文件中使用的所有插件,用于监听 webpack构建生命周期的各种事件。  

  (3)从配置文件的 entry入口开始解析文件的,递归找到每个文件依赖的文件,构建AST语法树。

  (4)在递归解析文件的过程中,根据文件的类型和 loader的配置,用loader对象进行转换。

  (5)递归得到每个文件的最终结果,根据ertry的配置,生成chunk

  (6)输出所有 chunk 到对应的文件目录。

  在构建过程中,配置中的plugin会在合适的时间做合适的事情。

  【常用插件】

  ExtractTextPlugin :从bundle 中提取特定的text到一个文件中。

  DefinePlugin :允许创建一个在编译时可以配置的全局变量,这使得一个应用可以打包编译出多个不同的应用。webpack 在打包编译时会对变量直接做文本替换,所以给定的字符串必须包含字符串本省的实际引号。JSON.string()。

  ProvidePlugin 插件,自动加载对应的模块,而不需要到处 通过import 或者 require 引入。

  CopyWebpackPlugin:将单个文件或者整个目录复制到构建目录

  HtmlWebpackPlugin 简化了 HTML 文件的创建,为应用生成一个 index.html,并添加一个script 脚本标签来加载生成的 bundle.js

  BudlieAnalyzerPlugin: 可视化的webpack 打包后文件的分析插件,作用:1.认识打包后的文件和大小;2.以便优化打包后的文件

  CommonsChunkPlugin :从 bundle中分离出公共的模块,便于缓存使用。

  

  

  

 

  

原文地址:https://www.cnblogs.com/wust-hy/p/10126513.html