前面的话
对于html-webpack-plugin这个插件,想必都不陌生。小柒在学习《深入浅出webpack》这本书时,书中介绍了web-webpack-plugin这一插件,是html-webpack-plugin的一个很好的替代品。下面来介绍一下这个插件。
作用
- 为单页应用生成 HTML
- 管理多个单页应用
使用
安装
npm install -D web-webpack-plugin
// 引用
const {WebPlugin} = require('web-webpack-plugin');
// 在配置文件中生成实例,并配置
plugins: [
// 使用webplugin,一个webplugin对应一个HTML文件
new WebPlugin({
template:'./template.html',// html模板文件所在的文件路径
filename: 'index.html'// 输出HTML的文件名称
})
]
配置文件
const path = require('path');
const {WebPlugin} = require('web-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
// app的javascript执行文件
app:'./main.js'
},
output: {
filename: '[name]_[chunkhash:8].js',
path:path.resolve(__dirname, './dist'),
},
module: {
rules: [
{
test: /\.js$/,
use:['babel-loader'],
// 排除node_modules目录的文件
exclude: path.resolve(__dirname, 'node_modules')
},
{
test: /\.css/,
use: [
MiniCssExtractPlugin.loader,
'css-loader']
}
]
},
plugins: [
// 使用webplugin,一个webplugin对应一个HTML文件
new WebPlugin({
template:'./template.html',// html模板文件所在的文件路径
filename: 'index.html'// 输出HTML的文件名称
}),
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
})
]
}
HTML模板
看一下template.html文件中的内容:
<html>
<head>
<meta charset="utf-8">
<!-- 注入Chunk app中的CSS -->
<link rel="stylesheet" href="app?_inline">
<!-- 注入google_analytics中的js代码 -->
<script src="./google_analytics.js?_inline"></script>
</head>
<body>
<div id="app"></div>
<!-- 导入chunk app 中的js -->
<script src="app"></script>
</body>
</html>
<script src="app"></script>
中的app就是配置文件中entry中的Chunk名称<link rel="stylesheet" href="app?_inline">
就是正常引入css文件一样引入webpack产生的代码。其中app?_inline的意思是:app表示CSS代码来自名叫app的Chunk,后面的_inline表示这些CSS代码要内嵌到HTML中。- 即URL字符里的问号前面部分表示资源内容来自哪里,后面的querystring表示这些资源注入的方式
当然也可以为这些资源配置其他的注入方式支持如下属性:
- _dist 只有在生产环境下才引入该资源
- _dev 只有在开发环境下才引入该资源
- _inline 把该资源的内容潜入到html里
- _ie 只有IE浏览器才需要引入的资源
例如app?_inline&_dist:表示只有在生产环境才能引入该资源,并且需要内嵌到HTML里。
运行后
运行之后可以看到dist目录下的生成了三个文件,其中的index.html就是web-webpack-plugin插件自动生成的一个html文件。
输出的index.html:
<html>
<head>
<meta charset="utf-8">
<!-- 注入Chunk app中的CSS -->
<style rel="stylesheet">h1 {
color: red;
}
</style>
<!-- 注入google_analytics中的js代码 -->
<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');</script>
</head>
<body>
<div id="app"></div>
<!-- 导入chunk app 中的js -->
<script src="app_e03d3bcd.js"></script>
</body>
</html>
最后,想体验完整的项目可以在xiaoqi的GitHub上拉取。