webpack(二) 根據模板生成簡單的html文件

(一)使用webpack 根據模板生成HTML,首先須要安裝插件 html-webpack-plugin。javascript

   在工程文件夾安裝插件 命令以下:html

npm install html-webpack-plugin --save-dev

 (二)java

   新建 webpack.config.js,名稱能夠更改,更改後 運行時,需指定 配置文件名稱。webpack

  例如,配置文件名爲 my.webpack.config.js, 則須要在package.json 文件中,在scripts 處添加以下代碼:web

"scripts": {
    "webpack": "webpack --config webapack.config.js --progress --display--modules --colors --dispaly-reason"
  }

  編譯時,需使用 npm run webpack 命令。npm

(三)編程

  webpack是支持 AMD、CMD、ES6模塊化編程的,所以,咱們是能夠使用 require、exports 來獲取、返回模塊內容的。json

  在webpack.config.js,添加以下代碼模塊化

  咱們將原始文件放在 /src/js 文件夾,打包複製後的文件放在 /dist/js 文件夾。ui

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.jsmain-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 文件 。

相關文章
相關標籤/搜索