Webpack修煉日誌——入門

DjangoXiang發表於2018-11-19

webpack快速入門

image

webpack 官方的解釋如下:

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

webpack是一個現代JS應用程式的靜態的繫結工具。其工作原理是構建專案各模組依賴關係的對映圖,並生成一個或者多個包。

在開始之前,我們先動手安裝。

安裝

npm install webpack webpack-cli -g
webpack --v
webpack --help
複製程式碼

此時,如果可以看到版本和命令幫助提示,則說明已經成功安裝。

初始化一個webpack的專案

# 首先確保有一個package.json的配置檔案
npm init
# 安裝webpack,並使之在開發時被使用到
npm install webpack webpack-cli -D
複製程式碼

當完成webpack的配置安裝後,package.json檔案中的devDependencies項中會有以下內容

    "webpack": "^4.25.1",
    "webpack-cli": "^3.1.2"
複製程式碼

此時說明 webpack和webpack-cli 已經配置到專案中。 我們再回到專案中建立一個src目錄,並隨便建立一個js檔案,儲存,在(專案目錄)命令列中執行

webpack --mode production

webpack會開始編譯,最後生成一個dist目錄

為了方便,我們在package.json編寫一個指令碼項

    "scripts":{
        "build":"webpack --mode production"
    }
複製程式碼

儲存。 在專案中建立一個src目錄,index.js檔案,儲存,在(專案目錄)命令列中執行

npm run build

然後會達成上述一樣到效果。

核心概念

入口 Entry

原文

An entry point indicates which module webpack should use to begin building out its internal dependency graph. webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

入口端:指出哪個模組可以讓webpack開始構建內部依賴圖,webpack將確定除了這個入口之外的模組和庫之間的直接或間接的依賴關係。

這就好比我們的專案有10個引用的類庫,然後這10個類庫又必須依賴500個基礎類庫,還有幾百個CSS的樣式依賴。猶如一團亂麻的線,你只需要告訴webpack,線頭在哪裡。剩下的工作就交給webpack把這個苦活髒活幹完。

而這個“線頭”,就是專案已開始啟動的那個.js檔案。在上述的案例專案中,就是src/index.js 檔案。webpack的預設入口檔案,就是專案目錄下src/index.js。但是你也可以自己指定給它一個入口檔案。這樣的話,就需要你在webpack的配置檔案中設定。// 詳見配置方法

輸出 Output

The output property tells webpack where to emit the bundles it creates and how to name these files. It defaults to ./dist/main.js for the main output file and to the ./dist folder for any other generated file.

對應輸入,輸出(output)則是讓webpack將輸入的“線頭”(即入口程式),整理完成之後,輸出到哪個位置上。預設是專案目錄下 ./dist/main.js ,相關的其他檔案,例如CSS、圖片等,則都放在 ./dist 目錄下

同樣的,你也可以通過配置檔案中的output項,來定義不同的輸出路徑。

載入器 Loaders

Out of the box, webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.

開箱即用,webpack(原生)僅能夠理解JS和JSON檔案,對於其他型別的檔案則需要通過類似於外掛的方式(注意,webpack還有一個外掛概念,雖然概念有點類似,但是作用不同)才能讓webpack能夠實現讀取,並且轉換為有效的模組,然後新增到依賴圖中。

比方說樣式表.css檔案,需要css-loader來處理。再比方說載入圖片.jpg,則需要url-loader來處理。

在使用loader時,有兩個比較關鍵的屬性用於配置。

  1. test屬性,圈定哪些檔案將被轉換。可以是檔名,或者用於匹配檔名的正規表示式。
  2. use屬性,指出使用什麼名字的載入器(loader)用於進行轉換。

webpack.config.js

module.exports = {
  output: {
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  }
};
複製程式碼

上面的案例,定義了rules(規則)屬性(test和use在是其屬性下的子屬性),含義是:所有的txt檔案,用raw-loader載入器進行轉換。

外掛 Plugins

While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.

In order to use a plugin, you need to require() it and add it to the plugins array. Most plugins are customizable through options. Since you can use a plugin multiple times in a config for different purposes, you need to create an instance of it by calling it with the new operator.

Loader相比較Plugin而言,功能較為單一。外掛可以做的則更多,例如優化、包管理和環境變數注入。要使用外掛,則需要用require()方法新增到外掛陣列中。大多數外掛可以通過配置項來實現定製。因為同一款外掛可以用在不同的地方實現不同的需求,所以外掛的使用需要用new來進行例項化。

目前流行的外掛如:

Mode 模式

By setting the mode parameter to either development, production or none, you can enable webpack's built-in optimizations that correspond to each environment. The default value is production.

通過mode引數,將專案設定為開發、生產、測試等模式,可以對應啟動不同環境下的配置。預設是生產模式(production)

瀏覽器相容性

webpack supports all browsers that are ES5-compliant (IE8 and below are not supported). webpack needs Promise for import() and require.ensure(). If you want to support older browsers, you will need to load a polyfill before using these expressions.

webpack支援所有符合ES5標準的瀏覽器。(不支援IE8(含)以下版本的瀏覽器)。webpack需要用到 Promise,用來import()方法和require.ensure()方法。如果是老的瀏覽器,則需要在使用這些表達之前載入polyfill。

配置檔案

webpack是根據開發者定義的配置檔案進行定義的。雖然把配置檔案放在這裡介紹,可能對於初學者來說有點“為時過早”。但是如果一點都不講,而直接將後續都概念,則又有一些“空中樓閣”。權衡之下,還是先講一講。如果遇到一些模糊都概念,可以暫時放下執著,繼續往後看,思路會變得越來越清晰。

webpack都配置檔案是一個js程式檔案,而這個程式檔案則是輸出了webpack工作都所需都所有配置項。這樣做的好處是比純粹靜態的檔案(如JSON)更靈活。如果沒有在配置檔案中設定,webpack則會採用預設配置替代。

配置檔案預設放在專案下,檔名為 webpack.config.js。它是一個標準的Node.js的CommonJS模組。所以,它支援:

  • 通過 require(...) 來匯入其他的程式檔案(模組)
  • 通過 require(...) 使用npm安裝的元件
  • 所有JS的語法和邏輯
  • 可以定義常量和變數
  • 可以通過執行一些方法來生成配置檔案中的部分配置項。例如可以根據不同的系統環境來指定訪問的埠號(這個常用於實際開發中)

官方還建議,應該避免如下操作

  • 不要用命令列方式,直接輸入引數
  • 留意不要將多個配置項的輸出值指向同一個檔案
  • 將一個配置檔案寫的太長,或者將一個大型專案的所有配置寫在一個檔案中。應該將其分模組化。

實際操作

接下來動手配置一個最最簡單的例子。作為一個全棧工程師,最簡單的後端就是express了,我們先建立一個express的初始化網站(專案)。在此之前,你要先確保你已經安裝了express腳手架。

npm i express-generator -g

express init
npm -i
複製程式碼

此時,一個空的express網站(預設是pug + jade)已經生成。在專案的根目錄下,編輯一個webpack的配置檔案 webpack.config.js

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './public/javascripts'),
    filename: 'index.bundle.js'
  }
}
複製程式碼

然後在專案下建立一個src目錄和一個index.js檔案,編輯這個程式檔案,往控制檯輸出一個hello world。這個檔案就是我們專案的入口檔案。上述的配置檔案,將輸出放在了/public/javascripts下的index.bundle.js。所以,我們需要在layout.jade中引入這個js檔案。

├── LICENSE
├── app.js
├── bin
│   └── www
├── package-lock.json
├── package.json
├── public
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
├── src
│   └── index.js
├── views
│   ├── error.jade
│   ├── index.jade
│   └── layout.jade
└── webpack.config.js
複製程式碼

在專案目錄中,執行webpack,看看是否有配置方面的問題。如果一切正常的化,差不多應該是這樣的畫面。

Hash: 69ed659021aa3734df11
Version: webpack 4.26.0
Time: 72ms
Built at: 2018-11-20 16:16:09
          Asset      Size  Chunks             Chunk Names
index.bundle.js  3.82 KiB    main  [emitted]  main
Entrypoint main = index.bundle.js
[./src/index.js] 54 bytes {main} [built]
複製程式碼

說明,webpack已經開始工作,並且將我們的js原始檔轉換後放到了public的javascripts目錄下了。好了,開啟網頁看看。(預設,express用的是localhost:3000)

images

相關文章