主要參考官網 Getting Started
Getting started
本篇主要介紹:
- 利用傳統用
script
載入js
寫程式的寫法 - 將 1. 的寫法改成利用
webpack
打包後的寫法
Create a bundle
建立一個叫 webpack-demo 的資料夾,並建立一個 node 專案,然後安裝 webpack
(建議裝在全域)
$ mkdir webpack-demo
$ cd webpack-demo
$ npm init -y
$ npm install --save-dev webpack
$ npm install --save-dev webpack -g # 或是裝在全域
檢查是否有安裝成功:
$ ./node_modules/.bin/webpack --help # Shows a list of valid cli commands
$ .\node_modules\.bin\webpack --help # For windows users
$ webpack --help # If you installed webpack globally
建立一個叫 app 的資料夾底下包含 index.js
function component () {
var element = document.createElement('div');
/* lodash is required for the next line to work */
element.innerHTML = _.join(['Hello','webpack'], ' ');
return element;
}
document.body.appendChild(component());
在 webpack-demo 底下建立一個 index.html
index.html
<html>
<head>
<title>webpack 2 demo</title>
<a href="https://unpkg.com/lodash@4.16.6">https://unpkg.com/lodash@4.16.6</a>
</head>
<body>
<a href="http://app/index.js">http://app/index.js</a>
</body>
</html>
以上我們利用 `` 的方式先將 lodash
載入後接著載入我們自己所寫的 index.js
。
在 index.js
中我們並沒有定義 _
,而是我們已經知道此變數在 lodash
已有定義此全域變數,因此我們所寫的程式碼才有辦法使用。
以上做法的缺點:
- 如果
lodash
沒有載入,或是載入順序與index.js
顛倒,會造成無法正確執行 - 當我們利用 `` 載入的資源一多,往往會非常難維護。因為我們可能不會很清楚知道我們載入的
js
宣告了什麼變數,很有可能會發生重複定義的情形;也有可能我們一不小心載入到很多我們其實沒用到的資源。
利用 Webpack
接下來我們就要利用 webpack
來解決這個問題。
在這裡,我們先把 webpack
想成一個可以幫我們將多個 js
打包壓縮後變成一個 js
的工具。之後我們的 index.html
要使用我們所寫的程式時,就不需要依序載入 lodash.js
index.js
,而是可以直接載入打包好的 js
。
開始打包
首先我們要在 index.js
中把 lodash.js
import 進來,並且打包成一個叫 bundle.js
的檔案。
首先先安裝 lodash
npm install --save lodash
接著我們修改 index.js
app/index.js
+ import _ from 'lodash';
function component () {
...
然後我們修改 index.html
index.html
<html>
<head>
<title>webpack 2 demo</title>
- <a href="https://unpkg.com/lodash@4.16.6">https://unpkg.com/lodash@4.16.6</a>
</head>
<body>
- <a href="http://app/index.js">http://app/index.js</a>
+ <a href="http://dist/bundle.js">http://dist/bundle.js</a>
</body>
</html>
接著開始打包 (假設我們一開始 install webpack 是裝在 global),此時我們就已經將 js
檔案打包好了,並可以開啟 index.html
。與一開始沒打包載入兩個 js 檔案的結果相同。
$ webpack app/index.js dist/bundle.js # 我們打包程式的 app/index.js(程式進入點) 到 dist 資料夾底下的 bundle.js
Using webpack with a config
隨著我們打包的設定越來越複雜,我們會建立一個 webpack.config.js
檔案來進行打包設定
webpack.config.js
var path = require('path');
module.exports = {
entry: './app/index.js', // 程式的進入點
output: {
filename: 'bundle.js', // 打包完的檔案名稱
path: path.resolve(__dirname, 'dist') // 打包到哪個資料夾
}
};
Using Webpack with npm
在 package.json
加入這段
package.json
{
...
"scripts": {
"build": "webpack"
},
...
}
接著我們只需執行 npm run build
即可進行打包
$ npm run build
得到相同的結果。