我们使用webpack-dev-server能够实现自动打包编译,生成的bundle.js在内存中,不被用户看到,还要设置script的src标签为 /bundle.js 才能实现自动打包编译。那么我们能否不用自动配置script的src属性呢?
使用webpack的插件,html-webpack-plugin能够实现在内存中创建index.html,并且不用设置script标签,这个插件自动为我们导入生成的bundle.js。
创建一个./src/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack</title>
<script src="/bundle.js"></script>
</head>
<body>
<ul>
<li>这是第1个li</li>
<li>这是第2个li</li>
<li>这是第3个li</li>
<li>这是第4个li</li>
<li>这是第5个li</li>
<li>这是第6个li</li>
<li>这是第7个li</li>
<li>这是第8个li</li>
<li>这是第9个li</li>
<li>这是第10个li</li>
</ul>
</body>
</html>
配置依赖,npm init
安装webpack、webpack-dev-server、html-webpack-plugin
创建要打包的文件:./src/main
import $ from 'jquery'
$(function () {
$('li:odd').css('backgroundColor','cyan');
$('li:even').css('backgroundColor','blue')
})
创建webpack.config.js,编写打包文件和打包完成文件
const path=require('path');
module.exports={
entry:path.join(__dirname,'./src/main.js'), //这是默认打包的文件
output:{ //这是默认打包生成的文件
path:path.join(__dirname,'./dist'), //文件路径
filename:'bundle.js' //文件名
},
devServer: { //dev-server的配置对象
open:true, //自动打开浏览器
contentBase:'src', //设置托管目录
port:3000, //设置端口
hot:true //启动热更新
},
};
在package.json中的"script":{...}创建:"dev":"webpack-dev-server --open --contentBase:src --port 3000 --hot",然后在终端输入" npm run dev"
这时我们将index.html中的<script src='bundle.js'></script>注释掉,发现
证明访问的这个index.html是在本地中,而不是在内存中的,不像使用webpack-dev-server自动打包编译的bundle.js是在内存中的,我们可以使用html-webpack-plugin来创建一个在内存中的index.html,它能自动将bundle.js导入到我们的index.html中。
1、html-wepack-plugin是什么?
这是一个webpack的插件,基于webpack来使用的。
2、html-webpack-plugin作用
html-webpack-plugin能够在内存中创建一个index.html,自动将webpack-dev-server打包生成内存中的bundle.js导入这个index.html。
3、html-webpack-plugin使用
3.1 安装
我们使用" cnpm i html-webpack-plugin -D"安装在项目文件中。
安装完成之后打开package.json可以发现我们的安装信息
3.2、配置
既然是一个基于webpack的插件,那么配置就肯定是要在webpack.config.js中进行的。
-
导入html-webpack-plugin模块-----const htmlWebpackPlugin=require('html-webpack-plugin')
-
在plugins:[]中创建一个 new htmlWebpackPlugin对象
-
在这个对象中传入配置参数:template:path.join(_disrname,'./src/index.html')----需要复制在内存中的文件路径 filename:'index.html'--------复制完成后的文件名
const path=require('path');
const htmlWebpackPlugin=require('html-webpack-plugin'); //导入模块
module.exports={
entry:path.join(__dirname,'./src/main.js'), //这是默认打包的文件
output:{ //这是默认打包生成的文件
path:path.join(__dirname,'./dist'), //文件路径
filename:'bundle.js' //文件名
},
devServer: { //dev-server的配置对象
open:true, //自动打开浏览器
contentBase:'src', //设置托管目录
port:3000, //设置端口
hot:true //启动热更新
},
plugins: [ //webpack的插件都在这里进行配置
new htmlWebpackPlugin({ //通过创建这样的对象,进行配置
template:path.join(__dirname,'./src/index.html'), //需要复制到内存的文件路径
filename:'index.html' //复制完成后的文件名
})
]
};
将index.html中的script删除后,运行 npm run dev(使用了webpack-dev-server的配置),
查看浏览器页面源码可以发现
html-webpack-plugin生成的index.html是在内存中的,它会自动为我们导入由webpack-dev-server生成的bundle.js!!!