(一)使用webpack 根據模板生成HTML,首先需要安裝插件 html-webpack-plugin。
在工程文件夾安裝插件 命令如下:
npm install html-webpack-plugin --save-dev
(二)
新建 webpack.config.js,名稱可以更改,更改后 運行時,需指定 配置文件名稱。
例如,配置文件名為 my.webpack.config.js, 則需要在package.json 文件中,在scripts 處添加如下代碼:
"scripts": { "webpack": "webpack --config webapack.config.js --progress --display--modules --colors --dispaly-reason" }
編譯時,需使用 npm run webpack 命令。
(三)
webpack是支持 AMD、CMD、ES6模塊化編程的,因此,我們是可以使用 require、exports 來獲取、返回模塊內容的。
在webpack.config.js,添加如下代碼
我們將原始文件放在 /src/js 文件夾,打包復制后的文件放在 /dist/js 文件夾。
var htmlWebpackPlugin=require('html-webpack-plugin'); module.exports={ /* entry:'./src/scripts/main.js',*/ entry:{ main:'./src/scripts/main.js', //文件來源路徑 a:'./src/scripts/a.js' }, output:{ path:'./dist', filename:'js/[name]-[hash].js', //生成后的文件名 為 a-2ea5b2e9b258a8bbba73.js,main-2ea5b2e9b258a8bbba73.js
publicPath:'http://cdn.com' //publicPath 用於發布時,生成的羽毛 }, plugins:[ new htmlWebpackPlugin({ filename:'index.html', //通過模板生成的文件名 template:'index.html',//模板路徑 inject:false, //是否自動在模板文件添加 自動生成的js文件鏈接 title:'這個是WebPack Demo', minify:{ removeComments:true //是否壓縮時 去除注釋 } }) ] };
我們可以在模板 index.html 書寫類似 PHP、ASP.net 的語法格式。
模板index.html文件模板內容
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title><%=htmlWebpackPlugin.options.title%></title>
<script type="text/javascript" src="<%=htmlWebpackPlugin.files.chunks.main.entry%>"></script>
</head>
<body>
<div>
:<=JSON.stringify(htmlWebpackPlugin.files[key])>
<input type="text">
<% for(var key in htmlWebpackPlugin.options){%>
<%=key %>:<%=JSON.stringify(htmlWebpackPlugin.options[key])%>
<%}%>
<% for(var key in htmlWebpackPlugin.files){%>
<%=key %>:<%=JSON.stringify(htmlWebpackPlugin.files[key])%>
<%}%>
<script type="text/javascript" src="<%=htmlWebpackPlugin.files.chunks.a.entry%>"></script>
</div>
</body>
</html>
運行 webpack,即可生成HTML 文件 。
