webpack 入門例子

monica888888發表於2017-07-28

https://webpack.js.org/guides/getting-started/

     webpack作為打包工具,支援commonJS、AMD、ES6模組規範,我們可以使用它將多個HTML、CSS、js打包等單個或者多個檔案,以減少http請求。不僅如此,webpack還可以將程式碼分割,按需載入檔案。、

一、 開始

   你也許已經知道,webpack 通常用來編譯JavaScript modules。一旦安裝,你能和webpack 互動,或者來自 CLI or API. If you're still new to webpack, please read through the core concepts and this comparison to learn why you might use it over the other tools that are out in the community.

二、Basic Setup建立專案目錄、初始化npm、安裝webpack  

 1>mkdir webpack-demo && cd webpack-demo//建立一個目錄
2>npm init -y  //初始化
3>

npm install --save-dev webpack  //本地安裝webpack發現出錯,在windows下先安裝
npm install -g jshint:主要儲存在user Appdata下面有一些資料
再安裝
npm install --save-dev webpack  //本地安裝webpack發現出錯,在windows下先安裝
:在這裡安裝時,會讀取user Appdata裡面的資料
不知道什麼原因?

三、建立一個簡單工程,目錄如下

webpack-demo  |- package.json+ |- index.html+ |- /src+   |- index.js

lodash@4.16.6
1、建立src/index.js  
function component() {
  var element = document.createElement('div');
  // Lodash, currently included via a script, is required for this line to work
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');
  return element;
}
document.body.appendChild(component());
2、建立index.html,並引進index.js
<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.16.6"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>
在index.html 例子中,兩個 <script> 標籤存在著依賴。index.js檔案依賴 lodash,這是因為index.js從來沒有表示需要lodash的;lodash認為是全域性變數。

這種方式管理js有幾個問題:

  • 指令碼依賴外部庫,並不明顯。
  • 如果一個依賴丟失了,或順序錯了,哪麼一個應用將出現問題。
  • 如果包含一個依賴,沒有使用,瀏覽器將強迫下載一個不必要的程式碼,即冗餘也浪費時間。

四、 webpack 建立工程,管理這些js,上面工程稍加修改

  Creating a Bundle

     首先,我們將稍微來調整我們的目錄結構,加一個釋出目錄/dist,建立一個index.html放在下面,即把原始碼和釋出程式碼分開,原始碼是我們寫和編輯的程式碼,釋出程式碼是最終瀏覽器載入的最小及最優化程式碼

  1、  project

webpack-demo
  |- package.json
+ |- /dist
+   |- index.html
- |- index.html
  |- /src
    |- index.js
 繫結 index.js 依賴 lodash.js ,我們需要安裝lodash,

  2、D:\setupsoft\nodejs\webpack-demo>npm install --save lodash

   然後修改 src/index.js,加下面一句 裡面,而以前是直接放在script裡,這樣從字數上來簡單多了,而且像java一樣

這一句和node.js的require()應該一樣?全是一個js檔案需要其它js檔案,匯入進來。

 import _ from 'lodash';

現在,因為我們已經繫結了我們的指令碼,我們必須修改我們的index.html 檔案. 刪除lodash <script>, 因為我們現在匯入了這個指令碼, 3、import it,修改另一個 <script>標籤去裝載繫結, 代替 raw /src 檔案:

<html>
   <head>
     <title>Getting Started</title>
   </head>
   <body>
   <script src="bundle.js"></script>
   </body>
  </html>
在這種安裝中, index.js 確定需要 lodash 出現, 並且用 _ 繫結它 (no global scope pollution).通過說明一個模組需要什麼依賴, webpack 能使用這個資訊去繫結一個依賴圖, 然後使用圖形去產生一個優化繫結,哪裡指令碼將按正確的順序執行。

也就是說,讓我們執行webpack,用我們 script 作為輸入, bundle.js所為輸出。

4、D:\setupsoft\nodejs\webpack-demo\node_modules\.bin>webpack ../../src/index.js ../../dist/bundle.js,

在dist釋出目錄建立一個bundle.js包

Hash: 5091f71fee92b3f8f6e9
Version: webpack 3.4.1
Time: 452ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] D:/setupsoft/nodejs/webpack-demo/src/index.js 296 bytes {0} [built]
   [1] ../lodash/lodash.js 540 kB {0} [built]
   [2] ../webpack/buildin/global.js 509 bytes {0} [built]
   [3] ../webpack/buildin/module.js 517 bytes {0} [built]

5、Your output may vary a bit, but if the build is successful then you are good to go.

在你的瀏覽器開啟 index.html  if everything went right, you should see the following text: 'Hello webpack'.



總結:上面就是把一個網頁有依賴關係的的幾個js,經過打包,然後生成一個bundle.js,引入到html中

          優點:1》可以加快瀏覽器取到一個檔案速度,使用者的響應時間縮短

                     2》減少頁面的程式碼量。

                     3>而且位元組數變少了。

Modules:

   The import and export 語句在ES2015在被標準化。然而在大多數瀏覽器儘管並不被支援 , webpack 並不支援他們 out of the box.

在這種情況下, webpack 實際上 "transpiles" 轉換程式碼,以便於老的瀏覽器也能執行它。如果你檢視dist/bundle.js, 你也許能看見webpack如何做這件事, it's quite ingenious!

除了import and export, webpack 支援各種其它的模板語法, see Module API for more information.

注:除了import and export 語句,webpack 並不改變任何程式碼,如果你正在使用其它的ES2015 features, 確定使用use a transpiler such asBabel orBublé via webpack'sloader system.


五、使用配置檔案建立工程,

  大多數工程將需要一個更復雜的安裝,這就webpack支援一個配置檔案的原因。這個比控制檯打許多命令更有效,
因此讓我建立一個替代上面使用得CLI選項。

  1、project

  加一個 webpack.config.js

webpack-demo
  |- package.json
+ |- webpack.config.js
  |- /dist
    |- index.html
  |- /src
    |- index.js
webpack.config.js  
const path = require('path');//匯入path下的所有檔案,是import
module.exports = {
  entry: __dirname+'/src/index.js',  
  output: {
    filename: 'bundle.js',//出
    path: path.resolve(__dirname, 'dist')//全域性變數,取得dist資料夾目錄
  }
};
現在,讓我們再一次使用我們新的配置檔案建立bundle.js:

./node_modules/.bin/webpack --config webpack.config.js
Hash: ff6c1d39b26f89b3b7bb
Version: webpack 2.2.0
Time: 390ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] (webpack)/buildin/module.js 517 bytes {0} [built]
   [3] ./src/index.js 278 bytes {0} [built]

如果一個webpack.config.js 存在, the webpack 命令 預設的選擇它. 這裡我們使用--config選項,僅僅去顯示

你能用一些name進行配置. 這個遲早用得上,為更復雜的配置,這個配置需要拆分成多個檔案。

 一個配置檔案允許更靈活比簡單的CLI使用。我們能夠指定裝載規則,外掛,

resolve options and many other enhancements this way. See the configuration documentation to learn more.

NPM Scripts

 我們讓上面命令更短: npm run buildh,是不是短很多,配置如下。

我們可以通過npm script:修改package.json

package.json  

{
  ...
  "scripts": {
    "build": "webpack"
  },
  ...
}

現在 npm執行build 命令。 Note 在scripts裡 we can reference locally installed npm packages by name instead of writing out the entire path. 、

This convention is the standard in most npm-based projects and allows us to directly call webpack, instead of./node_modules/.bin/webpack

Now run the following command and see if your script alias works:

npm run buildh

Hash: ff6c1d39b26f89b3b7bb
Version: webpack 2.2.0
Time: 390ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] (webpack)/buildin/module.js 517 bytes {0} [built]
   [3] ./src/index.js 278 bytes {0} [built]
Custom parameters can be passed to webpack by adding two dashes between the npm run build command and your parameters, e.g. npm run build -- --colors.

Conclusion

Now that you have a basic build together you should move on to the next guide Asset Management to learn how to manage assets like images and fonts with webpack. At this point, your project should look like this:

project

webpack-demo
|- package.json
|- webpack.config.js
|- /dist
  |- bundle.js
  |- index.html
|- /src
  |- index.js
|- /node_modules
If you're using npm 5, you'll probably also see a package-lock.json file in your directory.

If you want to learn more about webpack's design, you can check out the basic concepts and configuration pages. Furthermore, the API section digs into the various interfaces webpack offers.






相關文章