webpack(二) 根據模板產生簡單的html檔案

來源:互聯網
上載者:User

標籤:json   cdn   安裝外掛程式   dev   comment   font   ring   配置   options   

(一)使用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 檔案 。

 

 

 

 

 

 

 

 

 

webpack(二) 根據模板產生簡單的html檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.