Webpack學習筆記 - 提高篇

若是你已經讀了 Webpack學習筆記 - 入門篇,是否是以爲已經能夠用 Webpack 作些事情了。javascript

是的,可是總覺的少了些麼。餡裏不僅有肉,還有香菇。css

開始使用Webpack

  1. 安裝 html-webpack-plugin 插件html

    npm install html-webpack-plugin --save-dev
  2. 修改 index.html 文件java

    <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="utf-8">
         <title>Webpack Sample Project</title>
     </head>
     <body>
         <div id='hello'></div>
     </body>
     </html>
  3. 修改 webpack 配置文件 webpack.config.jswebpack

    var HtmlWebpackPlugin = require("html-webpack-plugin");
    
     module.exports = {
         entry: "./src/index.js",  //入口文件
         output: {
             path: "./dist/",           //打包輸出目錄
             filename: "js/index.js",    //打包文件名
             publicPath: "./"     //資源發佈路徑
         },
         module: {
             loaders: [
             {
                 test: /\.css$/, //處理樣式文件
                 loaders: ['style', 'css']
             },
             {
                 test: /\.json$/,  //處理json文件
                 loader: 'json' 
             },
             {
                 test: /.*\.(gif|png|jpe?g|svg)$/i, //處理圖片
                 loaders: [
                 'url?limit=8192&name=img/[name].[ext]',
                 'image-webpack?{optimizationLevel: 7, interlaced: false, pngquant: { quality: "65-90", speed: 4},  mozjpeg: { quality: 65 }}'
                 ]
             } 
             ]
         },
         plugins: [
             new HtmlWebpackPlugin({
                 filename: 'index.html', 
                 template: './index.html',
                 inject: true 
             })
         ]
     }
  4. 項目根目錄下執行 webpack 指令,輸出結束以下git

    Hash: fc21ebafad12332c7fd1
     Version: webpack 1.14.0
     Time: 7015ms
             Asset       Size  Chunks             Chunk Names
     img/webpack.png      40 kB          [emitted]
         js/index.js     291 kB       0  [emitted]  main
         index.html  243 bytes          [emitted]
     [0] ./src/index.js 258 bytes {0} [built]
     [8] ./src/hello.js 180 bytes {0} [built]
         + 8 hidden modules
     Child html-webpack-plugin for "index.html":
             + 3 hidden modules

    輸出目錄 dist 結構以下:github

    webpack-test-project
    |--dist
    |  |--index.html
    |  |--js
    |  |  |--index.js
    |  |--img
    	|  |  |--webpack.png

    文件 dist/index.htmlhtml-webpack-plugin插件以 index.html 爲模板自動生成:web

    <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="utf-8">
         <title>Webpack Sample Project</title>
     </head>
     <body>
         <div id='hello'></div>
         <script type="text/javascript" src="./js/index.js"></script>
     </body>
     </html>
  5. 查看結果npm

    瀏覽器打開 dist/index.html 文件,點擊看效果json

小結

  1. 插件可以完成 loader 所不能完成的任務。

附錄

  1. html-webpack-plugin
  2. list of plugins
相關文章
相關標籤/搜索