在初识webpack 中提到了webpack的基本配置和使用,接下来将进一步学习webpack在项目中的使用。
一.webpack生成简单的HTML页面
前面提到将需要打包的js文件打包成bundle.js后,需要在index.html中引入
此时如果我们将bundle.js换成a.js呢,也就是改变打包后输出文件的名称,那么只有一个办法,那就是到index.html中手动修改script便签的src属性值,那么如果生成的是多个呢,岂不是每添一个输出都要手动在页面中引入一个js,这样就给我们带来了相当大的工作量,有没有好的办法解决呢,npm为我们提供了一个贴心的插件——html-webpack-plugin
首先,通过命令行安装html-webpack-plugin,使用命令 npm install html-webpack-plugin
安装完成后,我们再来看输出多个js打包文件的情况
好此时我们运行webpack
生成两个打包后的js文件main.js和a.js,以及新的index.html文件
打开新生成的index.html文件
插件的其他属性介绍
二.参数传递
下面有这样的需求,加入我们需要将一些参数在config文件中定义,并且需要将其通过html-webpack-plugin插件传递,怎么操作呢
运行webpack后得到a.html,我们打开来看
那么html-webpack-plugin可以设置和传递那些参数呢
那么我们项目需要上线时如何操作呢
minify文档地址——点击打开链接
三.webpack处理多页面应用
以上两部分都是在介绍生成单页面并自动引入打包文件的,那么生成多页面的并且给不同的页面引入不同的打包文件如何实现呢
还是从配置文件下手,假设要生成页面a,b,c,同时需要的打包的js文件也有a,b,c
这样来实现
var htmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
entry:{
main:'./src/script/main.js',
a:'./src/script/a.js',
b:'./src/script/b.js',
c:'./src/script/c.js'
},
output:{
path:'/webpackDemo/dist',
filename:'js/[name].js',
publicPath:'http://cdn.com'
},
plugins:[
new htmlWebpackPlugin({
filename:'a.html',
template:'index.html',
inject:'head',
title:"this is a",
chunks:['main','a']
}),
new htmlWebpackPlugin({
filename:'b.html',
template:'index.html',
inject:'head',
title:"this is b",
chunks:['b']
}),
new htmlWebpackPlugin({
filename:'c.html',
template:'index.html',
inject:'head',
title:"this is c",
chunks:['c']
})
]
}
三个html好实现,无非就是三个new htmlWebpackPlugin(),那么给三个html文件分别引入不同的打包文件如何实现呢,用chunks,具体使用方法参照程序。