插件plugin
loader 用于转换某些类型的模块,而插件则可以用于执行范围更广的任务。包括:打包优化,资源管理,注入环境变量。
可以这样理解: loader的关注点在某种类型的文件编码解析上,插件plugin是关注某一个功能点:比如托管服务器,错误语法检测,挂载打包代码到模板文件等等.
想要使用一个插件,你只需要 require() 它,然后把它添加到 plugins 数组中。多数插件可以通过选项(option)自定义。你也可以在一个配置文件中因为不同目的而多次使用同一个插件,这时需要通过使用 new 操作符来创建一个插件实例。
EslintWebpackPlugin
eslint插件是一个非常强大的语言查错工具, vscode 编辑器中有提供 eslint 插件,下载插件并启用,自动就可以检测代码的语法错误,但是它只在你写代码的时候提示,我们希望打包项目的时候有相关提示,就可以配置它.
eslint-webpack-plugin插件就是使用 eslint 来查找和修复 JavaScript 代码中的问题。
eslint-webpack-plugin 3.0 仅支持 webpack 5。对于 webpack 4 请查看 2.x 分支。
环境准备:
npm install eslint-webpack-plugin --save-dev
如果未安装 eslint >= 7 ,你还需先通过 npm 安装:
npm install eslint --save-dev
插件配置:
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
// ...
plugins: [new ESLintPlugin(options)],
// ...
};
//options的参数配置:
context:__dirname+"/src" //指定文件根目录
extensions:String|Array[String] //指定需要检查的扩展名.不配置默认为"js"
exclude:"node_modules" //指定需要排除的文件及目录。必须是相对于 options.context 的相对路径。
files:String|Array[String] //指定目录、文件或 globs ,必须是相对于 options.context 的相对路径。 如果是目录则递归查找所有匹配 options.extensions 选项的文件。
HtmlWebpackPlugin
HtmlWebpackPlugin 简化了 HTML 文件的创建,以便为你的 webpack 包提供服务。这对于那些文件名中包含哈希值,并且哈希值会随着每次编译而改变的 webpack 包特别有用。你可以让该插件为你生成一个 HTML 文件,使用 lodash 模板提供模板,或者使用你自己的 loader。
安装:
npm install --save-dev html-webpack-plugin
插件配置:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: 'index.js',
output: {
path:__dirname+'/dist',
filename: 'bundle.js',
},
plugins: [new HtmlWebpackPlugin()],
};
//该插件将为你生成一个HTML5 文件, 在 body 中使用 `script` 标签引入你所有 webpack 生成的bundle.js。
//但是每次生成的模板都是新的
如果希望用自己的html文件作为模板
可以在参数中进行配置: https://github.com/jantimon/html-webpack-plugin#options
module.exports = {
entry: 'index.js',
output: {
path:__dirname+'/dist',
filename: 'bundle.js',
},
plugins: [new HtmlWebpackPlugin({
title: "hqyj-app", //html的标题默认为"Webpack App",
filename: "index.html", //模板html打包后生成的文件名,放在output.path里面,默认"index.html"
template: __dirname + "/public/index.html", //模板html文件的路径,
inject: "body", //'head' || 'body' 打包后的bundle挂载到模板html的位置:'body' 放置在body元素的底部。'head'将把脚本放在head元素中。,
publicPath: "./", //The publicPath used for script and link tags,
favicon:__dirname + "/public/favicon.ico", //打包前前前小图标的路径,默认为:"",
//"洗澡":压缩项配置
// minify:true,
minify: {
collapseWhitespace: true, //是否压缩HTML:空格回车
keepClosingSlash: true,//在单元素上保留末尾的斜杠
removeComments: true, //是否清除HTML注释
removeRedundantAttributes: true,
removeScriptTypeAttributes: true, //是否删除script的type属性(这个属性对于现代浏览器没啥用)
removeStyleLinkTypeAttributes: true, //是否删除< style>和< link>的type="text/css"
minifyJS: false, //是否压缩页内JS ,
minifyCSS: true //是否压缩页内CSS
},
cache:true,//仅当文件被更改时才重新打包,否则使用上一次打包时缓存起来的,默认true
})],
};