webpack2使用ch4-向根目录index.html文件传参并使用参数 使用线上资源 压缩html
1 webpack.config.js
const webpack = require('webpack'),
htmlWebpackPlugin = require('html-webpack-plugin'),
path = require('path');
module.exports = {
entry: {
main: './src/script/main.js',
a: './src/script/a.js'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'js/[name]-[chunkhash].js',
publicPath: 'http://cdn.com/' //path输出的时候的目录 publicPath理解为占位符,需要上线地址
},
plugins: [
new htmlWebpackPlugin({
//filename: 'index-[hash].html',
filename: 'index.html', //避免每次生成不同名的.html此时每次都会生成 index.html
template: 'index.html',
//inject: 'head',
inject: false,
title: 'webpack is good module pack',
date: new Date(),
minify: { //对当前的html文件进行压缩
removeComments: true, //删除注释
collapseWhitespace: true //删除空格
}
})
]
};
2 根目录 index.html
这里的.html同.ejs模板一样,可以使用js语法 <%= %> <% %> 、let in 、循环等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
<script type="text/javascript" src="<%=htmlWebpackPlugin.files.chunks.main.entry %>"></script>
</head>
<body>
<%= htmlWebpackPlugin.options.date %>
<% for(let key in htmlWebpackPlugin) {%>
<%= key %>
<% } %>
<!--注释内容-->
<script type="text/javascript" src="<%=htmlWebpackPlugin.files.chunks.a.entry %>"></script>
</body>
</html>
3 编译


<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>webpack is good module pack</title><script type="text/javascript" src="http://cdn.com/js/main-723f6c1682e09396ec6f.js"></script></head><body>Wed Apr 05 2017 21:49:33 GMT+0800 (中国标准时间) files options<script type="text/javascript" src="http://cdn.com/js/a-28982e930ed9e24890a5.js"></script></body></html>
可以看到压缩、传参、 header body不同地方引入js、(线上)都以实现

浙公网安备 33010602011771号