您的位置:首页 > Web前端 > HTML

webpack4+学习笔记:4. html-webpack-plugin 插件 与 clean-webpack-plugin 插件

2019-01-21 11:15 716 查看

html-webpack-plugin 插件 与 clean-webpack-plugin 插件

一、 html-webpack-plugin 插件
作用:将 html 打包到 dist 下可以产生自动引入生产的js
1. 安装

//终端输入
npm install html-webpack-plugin -D

查看 package.json 显示已安装成功

(2)webpack.config.js 配置

let path = require("path");

let HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
entry : "./src/index.js",
output: {
filename: "[name].[hash:8].js",
path    : path.resolve("./dist")
},
devServer: {
contentBase: "./dist",           //指定打开的页面
open: true,               	     //自动打开浏览器
host: "192.168.88.103",          //设置ip,不设默认 localhost
port: 8081,    					 //设置端口号
compress   : true,               //启动服务器压缩
},
module: {

},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
title   : "webpack-study",		//如何使用请看下面的补充
hash    : true,                 //清缓存用
}),
],
mode: "development",
resolve: {

}
}

终端执行:

npm run build

终端输出结果如下:


查看项目目录,我们可以看到:

打开 dist 下的 index.html 我们可以看到一起打包的js文件已经帮我们引入

综上,打包成功!!!

补充
这里在webpack.config.js 中我们给打包出来的 html 页面设置了 title,接下来请看如何让它显示在网页中:
修改 src 下的 index.html 的 title 标签:

<title><%=htmlWebpackPlugin.options.title%></title>

注意!!!是src下的index.html,不要修改成dist下的index.html !!!
重新打包

npm run build

点开 dist/index.html 可以看到

执行

npm run dev

打开网页可以看到


因此,标题已修改成功。

html-webpack-plugin 插件的更多了解,请看官方文档学习

二、clean-webpack-plugin 插件
作用:每次打包清除 dist 文件夹,然后重新把打包生成的文件放进去
1. 安装

//终端输入
npm install clean-webpack-plugin -D

查看 package.json 文件如下,显示安装成功

2. webpack.config.js 配置

let path = require("path");

let HtmlWebpackPlugin = require("html-webpack-plugin");

let CleanWebpackPlugin = require("clean-webpack-plugin");		//重置打包文件夹

module.exports = {
entry : "./src/index.js",
output: {
filename: "[name].[hash:8].js",
path: path.resolve("./dist")
},
devServer: {
contentBase: "./dist",           //指定打开的页面
open: true,               //自动打开浏览器
host: "192.168.88.103",   //设置ip,不设默认 localhost
port: 8081,               //设置端口号
compress: true,               //启动服务器压缩
},
module: {

},
plugins: [
new CleanWebpackPlugin("./dist"),   //重置打包文件夹
new HtmlWebpackPlugin({
template: "./src/index.html",
title: "webpack-study",
hash: true,                 //清缓存用
}),
],
mode: "development",
resolve: {

}
}

3. 执行命令查看
(1)执行运行命令的时候 dist 文件夹会被删除

npm run dev


(2)执行打包命令,生成 dist 文件夹

npm run build


关于 clean-webpack-plugin插件,请看官方文档

这一节的两个插件的学习就到这儿了~~~

下一篇进入热更新和拷贝文件的学习~~~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: