您的位置:首页 > Web前端 > HTML

webpack---htmlWbpackPlugin插件在webpack中的应用

2017-06-01 00:04 921 查看

安装

cnpm install html-webpack-plugin


配置

title://生成的html文件的title

filename://生成的html文件名字

template://webpack引入的源html文件,2.0允许使用任何loader:直接使用字符串路劲(./index.html);前置loader(!!handlebars!./index.hbs);配置module.loader使用。

inject: //添加位置:false-不添加,true-自动添加,head-添加至头部,body-添加至body

favicon://图标路径

minify://{options},collapseWhitespace压缩去除空格,minifyJS压缩JS等等;

hash://true代表给所有webpack打包的css js文件添加hash值,false反之

cache://true代表仅打包更改的文件

showError://true时候错误信息将会被备注于html中

chunks://当前htmlWebpackPlugin对象中引入当前html文件所需的chunk块;

chunksSordMode://分类

excludeChunks://除了value(chunk数组)值外都引入;

xhtml://默认false


使用

webpack.config.js:

const htmlWebpackPlugin=require('html-webpack-plugin');
const path=require('path');

module.exports={
entry:'./src/a.js',
output:{
path:path.resolve('./dist'),
filename:'js/bundel.[name].js'
},
plugins:[
new htmlWebpackPlugin({
template:'a.html',
filename:'a1.html',
})
]
}


a.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>


运行webpack,dist目录下得到a1.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src='./dist/bundel.a.js'></script>
</body>
</html>


绑定数据

htmlwebpackplugin插件支持在源html文件中像template语法一样给视图绑定数据

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title  %></title>
</head>
<body>
<%= htmlWebpackPlugin.options.data%>
</body>
</html>,


webpack.config.js:

const path=require('path');
const htmnlWbpackPlugin=require('html-webpack-plugin');
module.exports={
entry:'./src/script/b.js',
output:{
path:path.resolve('./dist'),
filename:'js/[name].bundle.js',

},
plugins:[
new htmnlWbpackPlugin({
template:'index.html',
filename:'home.html',
inject:false,
title:'webpack',
data:'aaaaaa'
})
]
}


运行webpack,得到home.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack</title>
</head>
<body>
aaaaaa
</body>
</html>,


多组html打包

webpack.config.js:

const path=require('path');
const htmnlWbpackPlugin=require('html-webpack-plugin');
module.exports={
entry:{page1:'./src/script/b.js',
page2:  ['./src/script/main.js','./src/script/a.js']
},
output:{
path:path.resolve('./dist'),
filename:'js/[name].[hash].js',
publicPath:'http://cdn.com/'
},
plugins:[
new htmnlWbpackPlugin({
template:'index.html',
filename:'home.html',
chunk:['page1','page2'],
title:'webpack is good',
data:'aaaaaa'
}),
new htmnlWbpackPlugin({
filename:'product.html',
template:'pro.html',
excludeChunks:['page2']
})
]
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息