若是你已經讀了 Webpack學習筆記 - 體驗篇,是否是有想進一步瞭解 Webpack
的衝動。css
沒有。那是由於包子太大,你尚未咬餡兒呢。html
Webpack
把項目當作一個總體,經過一個給定的入口文件 index.js
,從這個文件開始找到項目依賴的全部文件,而後使用 loaders
處理這些文件,最後將全部文件打包爲一個瀏覽器可識別的JavaScript文件 bundle.js
。jquery
將Webpack學習筆記 - 體驗篇中示例進行深加工。webpack
給 Webpack
增長配置文件 webpack.config.js
:git
module.exports = { entry: "./src/index.js", //入口文件 output: { path: "./dist/", //打包輸出目錄 filename: "bundle.js" //打包輸出文件名 } }
項目根據目錄下執行 webpack
指令,輸出結束以下:github
Hash: a4364839552719a85945 Version: webpack 1.14.0 Time: 629ms Asset Size Chunks Chunk Names bundle.js 278 kB 0 [emitted] main [0] ./src/index.js 92 bytes {0} [built] [2] ./src/hello.js 170 bytes {0} [built] - 1 hidden modules
輸出結果和最終效果與Webpack學習筆記 - 體驗篇中示例相同。web
給項目增長樣式文件、json數據文件、圖片npm
新建 src/hello.css
文件,內容以下:json
#hello { margin: auto; width: 80%; height: 500px; background-color: #00FF00; background-image: url(img/webpack.png); background-position: top center; background-size: 100% auto; background-repeat: no-repeat; line-height: 2.0em; font-family: 'Microsoft YaHei'; font-size: 2.0em; text-align: center; color: red; }
新建 src/hello.json
文件,內容以下:瀏覽器
{ "hello": "Hello Webpack, the Webpack test project! From Json." }
修改 hello.js
文件,內容以下:
var $ = require('jquery'); var json = require('./hello.json'); module.exports = function() { var hello = $('<div></div>'); hello.html(json.hello); return hello; };
修改 src/index.js
文件,內容以下:
var $ = require('jquery'); var logo = require('./img/logo.png'); var style = require('./hello.css'); var hello = require('./hello.js'); $('#hello').append('<img title="webpack logo" src="' + logo + '" /> Webpack logo'); $('#hello').append(hello());
新建 src/img
目錄,將 logo.png
和 webpack.png
拷貝至 img
目錄。
修改配置文件 webpack.config.js
以下
module.exports = { entry: "./src/index.js", //入口文件 output: { path: "./dist/", //打包輸出目錄 filename: "bundle.js", //打包文件名 publicPath: "./dist/" //資源發佈路徑 }, module: { loaders: [ { test: /\.css$/, //處理css文件 loader: 'style!css' }, { test: /\.json$/, //處理json文件 loader: 'json' }, { test: /.*\.(gif|png|jpe?g|svg)$/i, //處理圖片 loaders: [ 'url?limit=8192&name=[name].[ext]', 'image-webpack?{optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}, mozjpeg: {quality: 65}}' ] } ] } }
安裝 loader
模塊
npm install style-loader css-loader json-loader url-loader image-webpack-loader --save-dev
項目根目錄下執行 webpack
指令,輸出結束以下
Hash: 0b88a10526d6c19b7e49 Version: webpack 1.14.0 Time: 4701ms Asset Size Chunks Chunk Names webpack.png 40 kB [emitted] bundle.js 291 kB 0 [emitted] main [0] ./src/index.js 258 bytes {0} [built] [8] ./src/hello.js 179 bytes {0} [built] + 8 hidden modules
輸出目錄 dist
結構以下:
webpack-test-project |--dist | |--bundle.js | |--webpack.png
查看效果
瀏覽器打開 index.html
文件,點擊看效果
webpack.config.js
管理項目。loader
模塊,支持多種文件的打包處理。