学习webpack时,接触到了html-webpack-plugin这个插件,记一下使用方法
1、安装
npm install html-webpack-plugin --save-dev
2、使用,新建一个webpack.config.js文件
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: './src/script/main.js',
hello: './src/script/hello.js'
}, //打包的入口
output: { //文件打包后放入的地方
path: path.resolve(__dirname, './dist'), //打包放的文件路径,必须为绝对路径
filename: 'js/[name].[hash].js', //打包的文件的名字
publicPath: 'http://cd.com', //本地路径是js下面的文件,但是线上的时候会改变,所以要设置publicPath
},
plugins: [
new htmlWebpackPlugin({
template: 'index.html',
filename: 'index.html',
inject: true, //打包的文件在哪里插入head/body/true/false
title: 'this is wepack!',
})
]
}
[name]: entry里的main名称,
[hash]: npm run webpack打包后生成的hash
[chunckhash]: npm run webpack打包后每个文件的hash值(MD5值)只有文件被改动了才会生成新的chunkhash值,否则不会变
3、属性
template: 生成的文件依赖的模板
filename: 生成的文件的文件名
title: 生成的html文件的标题
如何在模板html中引用htmlWebpackPlugin配置的title属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
//获取htmlWebpackPlugin插件的title属性
<title><%= htmlWebpackPlugin.options.title%></title>
</head>
<body>
</body>
</html>
inject: head/body/true/false四个值,指定在何处引入script标签
favicon: './img/favicon' 生成文件的一个图标
minify: 对生成的文件进行压缩,值是一个对象
minify: { //对当前生成的文件进行压缩
removeComments: true, //删除注释
collapseWhitespace: false, //删除空格
removeAttributeQuotes: true //移除属性的引号
},
chunks: ['main']用于多入口文件,选择你要使用的js,值是一个数组,如果没有设置,默认所有js都会引入
excludeChunks: ['main'],你不需要使用的一些js,除此之外都会引入
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: './src/script/main.js',
hello: './src/script/hello.js'
}, //打包的入口
output: { //文件打包后放入的地方
path: path.resolve(__dirname, './dist'), //打包放的文件路径,必须为绝对路径
filename: 'js/[name].[hash].js', //打包的文件的名字
publicPath: 'http://cd.com', //本地路径是js下面的文件,但是线上的时候会改变,所以要设置publicPath
},
plugins: [
new htmlWebpackPlugin({
template: 'index.html',
filename: 'aaaa.html',
inject: true, //打包的文件在哪里插入head/body/true/false
title: 'wepack is good!',
favicon: '',
minify: { //对当前生成的文件进行压缩
removeComments: true, //删除注释
collapseWhitespace: false, //删除空格
removeAttributeQuotes: true //移除属性的引号
},
chunks: ['main'], //多页面应用时,chunks选择你要使用的那些js文件,
excludeChunks: ['hello'], //排除掉你不需要使用的js
}),
new htmlWebpackPlugin({
template: 'index.html',
filename: 'hello.html',
inject: true, //打包的文件在哪里插入head/body/true/false
title: 'this is hello!',
favicon: '',
minify: { //对当前生成的文件进行压缩
removeComments: true, //删除注释
collapseWhitespace: false, //删除空格
removeAttributeQuotes: true //移除属性的引号
},
chunks: ['hello'],
excludeChunks: ['main']
})
]
}