一. 什么是插件
随着应用程序的增长,如果继续手动地在 index.js 里面引入插件就会越来越困难,因此我们想要自动引入插件,那么就可以使用 webpack插件 。
webpack插件
什么是插件呢?webpack 就像一条生产线,要经过一系列的处理流程后,才能将入口文件转换为输出的结果。
例如上一篇中,入口文件 index.js,需要依赖于 hello-world1.js 和 hello-world2.js 两个 js 文件,而依赖的这两个 js 文件可能还会依赖于其他的 js 文件以及 css 文件,而 css 文件的引入,需要使用webpack loaders,也就是加载器。
webpack会把这些依赖关系记录下来,然后交给 webpack 编译器。
webpack 编译器经过加工以后,会生成目标文件,比如 css 和 js 文件。
webpack编译的过程,需要应用一些工具来帮忙,这些工具可以帮助webpack来执行一些特定的任务,比如打包优化、资源管理等等。这些工具就是 plugins插件
。
webpack官网里面可以看到webpack5里面使用的插件,主要分成了三组:Community,Webpack,Webpack Contrib。
Community
:社区的插件,比如 HtmlWebpackPlugin;
Webpack
:webpack内置的官方插件;
Webpack Contrib
:webpack 第三方插件。
二. 试一哈HtmlWebpackPlugin
- 安装
npm install html-webpack-plugin -D
(-D表示在本地开发环境安装)
2. 插件配置
(1) 尝试1:在上一节webpack.config.js
的基础上,加上plugins
配置。
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 关键
module export = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(_dirname, './dist')
},
mode: 'none',
plugins: [ // 关键
new HtmlWebpackPlugin();
]
}
指令npx webpack之后,就可以看到项目中生成了dist文件夹,里面有bundle.js和index.html。index.html的标签里面有一个script标签,引入了我们的入口文件,且这个html能在浏览器中正常打开和执行bundle.js的函数。
(2) 尝试2:
可以看到上面的尝试中,dist文件夹和src下都有一个index.html,但通过两个文件中的title不一样可以发现这俩index.html没什么关系。
接下来就是通过webpack.config.js的配置,来让编译后的index.html基于src下的index.html生成的。
在src下的index.html 中的script标签删除,在new HtmlWebpackPlugin中加入参数,如下。
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module export = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(_dirname, './dist')
},
mode: 'none',
plugins: [
new HtmlWebpackPlugin({
template: './html', // *模板是当前目录下的html,即src下面的index.html
filename: 'app.html', // *修改dist中的html为app.html
inject: 'body' // *将打包入口文件的引入位置放在<body>中,而不是之前的<head>中
});
]
}
运行npx webpack之后发现dist下面的app.html中title和src下的index.html一样,且引入的入口js文件也是在里面的了。
三、清理dist
刚刚的尝试2操作之后,会发现需要的 dist/app.html 确实增加了,但是之前的 dist/index.html 还是存在。因此我们想要清理掉不需要的文件。
可以在webpack.config.js中的 output 增加 clean: true
即可。
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module export = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(_dirname, './dist'),
clean: true // *清除不需要的
},
mode: 'none',
plugins: [
new HtmlWebpackPlugin({
template: './html',
filename: 'app.html',
inject: 'body'
});
]
}