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
相关文章
相关标签/搜索