webpack,二 根据模板生成简单的html文件

(一)使用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 >
    <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 文件 。