在上一篇中讲到了webpack的简单使用,从webpack的初始化,项目创建到项目编译,在本篇为大家讲解webpack如何打包html
目录
---------------------------
首先接着上一篇,我们就看一下项目的目录文件情况:
接着为大家讲解webpack中plugins插件的作用,在webpack中可以支持使用插件来扩展我们的webpack功能,例如在此篇文章中将为大家带来HtmlWebpackPlugin插件的使用,它的作用是使用一个html做为模板,来生成一个新的html文件,具体操作如下:
1.安装html-webpack-plugin插件
npm install --save-dev html-webpack-plugin
使用npm安装慢的同学可以使用cnpm,具体的安装方法请咨询我们的百度妹子
2.配置webpack.config.js添加插件
编辑webpack.config.js文件
'use strict'
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
index: './src/index.js'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
}
此处我们首先引入了html-webpack-plugin插件,并添加plugins配置
其中filename表示我们要生成的html文件名
template表示我们的html模板的位置,还记得上一篇中在根目录下创建的index.html文件吗?没错,就是它啦
接下来再编译试试
npm run dev
运行结果:
哈哈,从日志上我们已经看到生成了index.html文件,再到dist目录中看看
此时,已经生生了index.html文件,接着打开浏览器,运行一下index.html文件看看效果
哈哈,发现已经成功了,有木有?
此时我们观察index.html发现文件中除了模板html中的内容外,还将index.js中的内容也引入进来了
我们再试试给index.js换个名字
修改webpack.config.js文件,编辑entry下的index,改为app
'use strict'
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
app: './src/index.js'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
}
再次执行npm run dev
接着,发现script在body标签中,那么就有人问了,怎么放在head标签下?
回到webpack.config.js修改HtmlWebpackPlugin的构造参数,将 inject:true 改为 inject: 'head' 即可
'use strict'
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
app: './src/index.js'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'head'
})
]
}
再编译发现:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<title>demo</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body></body>
</html>
接着,如果我们需要动态的修改title需要怎么做呢?
其实HtmlWebpackPlugin是可以支持自定义参数的,比如:
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'head',
title: 'webpack-demo'
})
]
增加一个title参数,并修改index.html模板
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body></body>
</html>
再次编译:
哈哈,是不是很好玩呢?