Webpack 是 JavaScript 的模組建置工具,運行在 Node.js 上,它可以將零散的 JavaScript 檔案用各式工具優化並打包起來,加快網頁的載入時間。Webpack 也並不限於用在 JavaScript 上,舉凡網頁有用到的靜態資源(如 JS、CSS、圖片檔等),甚至是 HTML 網頁,Webpack 都有辦法打包。

Webpack 官方網站:

官方網站上給的一張圖例,簡潔扼要地說明了 Webpack 的功用:

Webpack 將模組打包成靜態資源的圖例

Webpack 的 Node.js 環境

Webpack 官方建議使用 Node.js 最新的 LTS 版本來運行 Webpack。Windows 的使用者可以直接到 Node.js 官方網站下載到 Node.js 的安裝檔,而 Linux 作業系統或是 macOS 的使用者可以參考這篇文章來安裝指定版本的 Node.js。

建立 Webpack 專案

Webpack 可以被加進現有的 Node.js 專案中,在終端機執行以下指令來安裝 webpack 和 webpack-cli 這兩個套件。

npm i -D webpack webpack-cli

指令中的 -D 參數即是 --save-dev。

接著在 package.json 中加入新的腳本指令:

{
    ...

    "scripts": {
        ...

        "build:webpack": "webpack --mode production",

        ...
      },

      ...
}

production 其實就是 Webpack 預設的模式,它會將 NODE_ENV 設為 production,並且會自動啟用它自帶的一些相關外掛。如果需要的話也可以使用 development,它會將 NODE_ENV 設為 development,也會自動啟用它自帶的一些相關外掛。

再來就是在 Node.js 專案根目錄中,新增 Webpack 的設定檔 webpack.config.cjs,內容可以初始如下:

module.exports = {
    plugins: [

    ],
    module: {
        rules: [

        ]
    },
};

使用 npm 指令打包 Webpack 專案

由於我們已經事先在 package.json 中加入 build:webpack 腳本指令了,因此可以直接使用 npm run build:webpack 指令來執行它。

進入點(Entry Point)和輸出

Webpack 會去執行某個或是某幾個 JavaScript 檔案作為進入點,預設的進入點只有一個,路徑為 src/index.js,且其輸出的 JS 檔案的預設路徑為 dist/main.js。搭配其它的載入器也可以使用非 JavaScript 作為進入點。

如果要修改進入點的路徑,要在 webpack.config.cjs 設定檔中,加上 entry 欄位,設定方式如下:

module.exports = {
    ...

    entry: "./path/to/js-file",

    ...
};

例如:

module.exports = {
    ...

    entry: "./src/lib.js",

    ...
};

至於進入點的 JS 程式寫法,稍後會再提到。

如果要修改輸出的 JS 檔案的路徑,要在 webpack.config.cjs 設定檔中,加上 output 欄位,設定方式如下:

module.exports = {
    ...

    output: {
        path: "/path/to/folder",
        filename: "./path/to/file",
    },

    ...
};

output 欄位中的 path 欄位表示要儲存輸出檔(不限於 JS 檔)的目錄,注意這個路徑必須要是絕對路徑!而 filename 欄位則是輸出的 JS 檔(其它類型的檔案會用其它方式設定)要儲存的路徑,注意這個路徑必須要是相對路徑,才能使輸出檔存在於 path 欄位的絕對路徑下。當然,如果您想要讓輸出檔放置在 Node.js 專案的根目錄下的 dist 目錄的話,可以不必設定 path 欄位。

例如:

const path = require("node:path");

module.exports = {
    ...

    output: {
        path: path.join(__dirname, "output"),
        filename: "./js/bundle.min.js",
    },

    ...
};

以上的 __dirname 即表示目前執行的 JS 檔案(此處即 webpack.config.cjs)的所在目錄之絕對路徑(此處即 Node.js 專案的根目錄)。

如果要設定多個進入點,entry 欄位和 output 欄位的設定方式如下:

const path = require("node:path");

module.exports = {
    ...

    entry: {
        "name-1": "./path/to/js-file-1",
        "name-2": "./path/to/js-file-2",
        "name-3": "./path/to/non-js-file-2",
    },
    output: {
        path: path.join(__dirname, "output"),
        filename: "./js/[name].min.js",
    },

    ...
};

在 filename 欄位的字串中加入 [name],可以讓 Webpack 自動用進入點的名稱來取代它。如果 entry 欄位有設定多個進入點,但是沒有設定 output 欄位的話,Webpack 預設的 output 欄位值如下:

const path = require("node:path");

module.exports = {
    ...

    output: {
        path: path.join(__dirname, "dist"),
        filename: "./[name].js",
    },

    ...
};

如果網頁的靜態資源有需要使用 CDN (Content Delivery Network),output 欄位值可以再加上 publicPath 欄位,來替輸出檔的網址連結加上前綴,如此一來在 HTML 或是 CSS 中有用到的靜態資源網址連結就可以被取代為 CDN 的網址連結。

例如:

const path = require("node:path");

module.exports = {
    ...

    output: {
        path: path.join(__dirname, "output"),
        publicPath: "https://cdn.example.com/",
        filename: "./js/bundle.min.js",
    },

    ...
};

為了確保 HTML 或是 CSS 的版本和其連結到的靜態資源的版本是一樣的,我們可以在 path 和 publicPath 欄位值的字串中使用 [fullhash],讓 Webpack 自動用專案的雜湊值來取代它。

例如:

const path = require("node:path");

module.exports = {
    ...

    output: {
        path: path.join(__dirname, "output", "[fullhash]"),
        publicPath: "https://cdn.example.com/[fullhash]/",
        filename: "./js/bundle.min.js",
    },

    ...
};

在打包前先清空目錄

Webpack 在打包專案前預設並不會先將輸出目錄清空,因此一不小心就會留有前次產生出來但現在已經沒有用到的檔案。若要讓 Webpack 將輸出目錄清空,可以將 output 欄位的 clean 屬性設為 true。

如下:

module.exports = {
    ...

    output: {
        ...

        clean: true,

        ...
    },

    ...
};

打包 JavaScript 檔案

Babel

現在開發 JavaScript 程式大多是靠 Node.js,Node.js 能夠支援的 ECMAScript 版本很新(可以查看這個網頁),但是主流的網頁瀏覽器對於比較新的 ECMAScript 語法並沒有完全支援(可以查看這個網頁)。所以為了使 Node.js 開發的 JavaScript 程式能夠在各大網頁瀏覽器上正常運行,我們需要使用「Babel」這套工具來轉換 JS 語法。

在終端機執行以下指令來安裝 babel-loader、@babel/core、@babel/register 和 @babel/preset-env 這四個套件。

npm i -D babel-loader @babel/core @babel/register @babel/preset-env

在 webpack.config.cjs 設定檔中,於 module 欄位的 rules 陣列內,加入 Babel 的載入器(loader)規則。Webpack 會去讀取進入點的 JS 檔案所 require 或是 import 的檔案,以及這些檔案再引用的檔案(例如被引用的 JS 檔案又去引用其它的 JS 檔案,或是被引用的 SCSS 檔案又去引用其它的 SCSS 檔案,又或是被引用的 CSS 檔案又去引用其它的圖片檔案),這些靜態資源的檔案路徑,除了 JS 檔案外,都必須要在 rules 陣列中被匹配到,並指派正確的載入器來負責處理,否則 Webpack 就無法成功打包專案。

雖然 JS 檔可不必寫在 rules 陣列中來匹配,但是如果我們要指定別的載入器就得要寫了。Babel 的載入器規則寫法如下:

module.exports = {
    ...

    module: {
        rules: [
            ...

            {
                test: /\.js$/iu,
                use: {
                    loader: "babel-loader",
                    options: { presets: ["@babel/preset-env"] },
                },
            },

            ...
        ]
    },

    ...
};

混淆與最小化 JS 程式

為了避免我們辛苦開發的 JavaScript 程式碼被輕易盜用,同時也希望 Webpack 打包出來的 JS 檔案可以愈小愈好,那就要替 Webpack 加上 terser-webpack-plugin 外掛。Webpack 預設就有啟用這個外掛,如果我們要更改它的設定值,就要手動在 webpack.config.cjs 設定檔中將其 require 進來,不過還要先執行以下指令將 terser-webpack-plugin 加入 devDependencies:

npm i -D terser-webpack-plugin

在 optimization 欄位中,其底下還有個 minimizer 欄位,值為一個陣列,接著將 terser-webpack-plugin 的實體加進 minimizer 欄位的陣列中。

如下:

const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
    ...

    optimization: {
        minimizer: [
            new TerserPlugin({
                extractComments: false,
                terserOptions: { format: { comments: false } },
            }),
        ]
    },

    ...
};

以上設定可以讓 npm run build:webpack 指令所輸出的 JS 檔案中完全沒有註解。

打包任意檔案

將檔案引用至 JavaScript 中

JavaScript 原先的 require 函數和 import 關鍵字只能夠引用 JavaScript 程式,但是在 Webpack 的框架下,它們要引用什麼樣的類型的檔案都是可以的。因此如果要打包非 JS 檔案的話,只要在進入點的 JS 檔案中,加上如以下的程式即可:

import './path/to/file';

檔案載入器

前面有提到過,靜態資源的檔案路徑,除了 JS 檔案外,都必須要在 webpack.config.cjs 設定檔中的 rules 陣列內被匹配到,並指派正確的載入器來負責處理,否則 Webpack 就無法成功打包專案。

Webpack 內建檔案載入器,稱為「資產模組」(Asset Module),分為如下幾種類型:

  • asset/resource:在輸出目錄產生引用到的檔案並修改 URL 指到那個檔案。
  • asset/inline:將檔案內容轉成 Data URI,嵌入至程式碼中。
  • asset/source:將檔案內容直接嵌入至程式碼中。
  • asset:根據檔案大小自動選擇要用 asset/inline 還是 asset/resource 來打包檔案。

在 webpack.config.cjs 設定檔中,於 module 欄位的 rules 陣列內,加入資產規則。若是要載入如 SVG、JPEG、PNG、GIF、WEBP 等網頁常用的圖片格式,以及 EOT、WOFF、WOFF2、TTF、OTF、SVG 等網頁常用的字型格式的話,規則如下:

module.exports = {
    ...

    module: {
        rules: [
            ...

            {
                test: /\.(eot|woff|woff2|[ot]tf)$/iu,
                type: "asset/resource",
                generator: { filename: "fonts/[name][ext]" },
            },
            {
                test: /.*font.*\.svg$/iu,
                type: "asset/resource",
                generator: { filename: "fonts/[name][ext]" },
            },
            {
                test: /^(?!.*font).*\.svg$/iu,
                type: "asset/resource",
                generator: { filename: "images/[name][ext]" },
            },
            {
                test: /\.(jpe?g|png|gif|webp)$/iu,
                type: "asset/resource",
                generator: { filename: "images/[name][ext]" },
            },

            ...
        ]
    },

    ...
};

如果想保留靜態資源檔案的檔名和副檔名,就如上面規則中,把 generator 的 filename 欄位值設為 xxx/[name][ext]。如果不設定 filename 欄位,就會以雜湊值當作是輸出檔名,將檔案輸出到輸出目錄底下。

打包 SCSS/CSS 檔案

SCSS 是用來產生 CSS 的程式,提供比 CSS 還要更方便的語法結構,也相容原本的 CSS。若您原先只用 CSS,在使用 Webpack 時改用 SCSS,可以讓 CSS 變得容易維護許多。SCSS (Sassy CSS)是 Sass 提供的一種新格式,而 Sass 原本在用的舊格式也稱為 Sass。

Sass/SCSS 的官方網站:

為了能夠讓 Webpack 在打包時候去解析 SCSS/CSS 檔案,我們不能直接指派檔案載入器來處理 SCSS/CSS 檔案。

Sass/SCSS/CSS 載入器

sass-loader 是一個能夠讀取 Sass、SCSS 和 CSS 檔案的載入器,檔案在被讀取後會被轉成 CSS 格式,可以在終端機執行以下指令來安裝。

npm i -D sass-loader sass

在 webpack.config.cjs 設定檔中,於 module 欄位的 rules 陣列內,加入 Sass/SCSS/CSS 載入器的規則。如下:

module.exports = {
    ...

    module: {
        rules: [
            ...

            {
                test: /\.(sa|sc|c)ss$/iu,
                use: ["sass-loader"],
            },

            ...
        ]
    },

    ...
};

在這邊的規則中,use 欄位值使用了陣列結構,表示要使用多個載入器。接下來繼續再介紹更多相關的載入器。

PostCSS 載入器

postcss-loader 是一個能對 CSS 做前處理的載入器。autoprefixer 是 postcss-loader 的外掛,可以自動添加所有網頁瀏覽器的 CSS 前綴。cssnano 也是 postcss-loader 的外掛,可以最小化 CSS。在終端機執行以下指令來安裝這些套件:

npm i -D postcss postcss-loader autoprefixer cssnano

在 webpack.config.cjs 設定檔中,於 sass-loader 之上,加入 PostCSS 載入器。如下:

module.exports = {
    ...

    module: {
        rules: [
            ...

            {
                test: /\.(sa|sc|c)ss$/iu,
                use: [
                    {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require("autoprefixer"),
                                    require("cssnano")({ preset: ["default", { discardComments: { removeAll: true } }] }),
                                ],
                            },
                        },
                    },
                    "sass-loader",
                ]
            },

            ...
        ]
    },

    ...
};

關於 autoprefixer 的作用,這邊再舉個例子。例如以下 CSS 語法:

.example {
    display: grid;
    transition: all .5s;
    user-select: none;
    background: linear-gradient(to bottom, white, black);
}

經過 postcss-loader 和 autoprefixer 處理後會變成:

.example {
    display: grid;
    -webkit-transition: all .5s;
    transition: all .5s;
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
    background: -webkit-gradient(linear, left top, left bottom, from(white), to(black));
    background: linear-gradient(to bottom, white, black);
}

如此一來就不必太擔心同一個 CSS 到不同的網頁瀏覽器上顯示出來會有很大的不同啦!

CSS 載入器

css-loader 才是真正讀取 CSS 的載入器,它會去尋找 CSS 中使用 @import 或是 url() 引用的其它 CSS 檔案或是圖片檔案,將它們也丟給 Webpack 一起打包。在終端機執行以下指令來安裝這個套件:

npm i -D css-loader

在 webpack.config.cjs 設定檔中,於 postcss-loader 之上,加入 CSS 載入器。如下:

module.exports = {
    ...

    module: {
        rules: [
            ...

            {
                test: /\.(sa|sc|c)ss$/iu,
                use: [
                    "css-loader",
                    {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require("autoprefixer"),
                                    require("cssnano")({ preset: ["default", { discardComments: { removeAll: true } }] }),
                                ],
                            },
                        },
                    },
                    "sass-loader",
                ]
            }

            ...
        ]
    },

    ...
};

輸出 CSS

光有 CSS 載入器的話會把 CSS 檔案包進 JS 檔案中一起輸出(若再加上 style-loader,就能讓 CSS 在 JS 執行之後被注入到 HTML 中,但筆者不太喜歡這樣的作法),如果要把 CSS 檔案從 JS 檔案中分離出來的話,我們還需要加上 mini-css-extract-plugin 這個外掛,可以在終端機執行以下指令來安裝。

npm i -D mini-css-extract-plugin

在 webpack.config.cjs 設定檔中,將 mini-css-extract-plugin 的實體加進 plugins 欄位的陣列中。

如下:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    ...

    plugins: [
        ...

        new MiniCssExtractPlugin({
            filename: "./path/to/css-file"
        }),

        ...
    ],

    ...
};

filename 欄位用來設定 CSS 檔案的輸出路徑,其設定方式和 JS 檔案的 filename 是一樣的。如果不設定 filename 欄位,預設值會是 ./[name].css。

接著也還需要在 webpack.config.cjs 設定檔中,於 css-loader 之上,加入 mini-css-extract-plugin 提供的載入器。

如下:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    ...

    module: {
        rules: [
            ...

            {
                test: /\.(sa|sc|c)ss$/iu,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require("autoprefixer"),
                                    require("cssnano")({ preset: ["default", { discardComments: { removeAll: true } }] }),
                                ],
                            },
                        },
                    },
                    "sass-loader",
                ]
            }

            ...
        ]
    },

    ...
};

移除無用的 CSS

現在開發網頁很少自己從無到有把 CSS 寫出來,通常會直接套用如 Bootstrap 等的 CSS 框架,但是我們不太可能將 CSS 框架提供的 CSS 全都應用上,肯定會留有完全沒有被使用到的 CSS 設定。這些沒有用到的 CSS 在沒有經過特殊處理的情況下也還是會被網頁瀏覽器給讀取,不僅會佔用伺服器流量,網頁的載入時間也會比較長。

為了移除沒有用到的 CSS,我們需要安裝 purgecss-webpack-plugin 外掛,以及方便用來取得檔案路徑的 glob 套件。可以在終端機執行以下指令來安裝這些套件:

npm i -D purgecss-webpack-plugin glob

在 webpack.config.cjs 設定檔中,將 purgecss-webpack-plugin 的實體加進 plugins 欄位的陣列中。

如下:

const path = require("node:path");
const glob = require("glob");
const { PurgeCSSPlugin } = require("purgecss-webpack-plugin");
	 
const PATHS = { views: path.resolve(__dirname, "/path/to/html-or-templates-folder") };

module.exports = {
    ...

    plugins: [
        ...

        new PurgeCSSPlugin({
            paths: glob.globSync(`${PATHS.views}/**/*`, {nodir: true}),
            safelist: {
                standard: [],
                deep: [],
                greedy: [],
            },
            blocklist: [],
        }),

        ...
    ],

    ...
};

以上程式中,用了 PATHS 變數來儲存一些固定、可能會被重複使用的路徑。views 這個路徑是用來放置 HTML 網頁檔案或是 HTML 模板檔案的目錄。在 purgecss-webpack-plugin 外掛的選項中,paths 欄位的值為多個路徑的字串陣列,一個路徑應指向一個純文字檔案,purgecss-webpack-plugin 會自動從這些路徑指到的多個純文字檔案中分析出現過的字詞,並記錄下來。如果 CSS 的元素名稱並沒有出現在這些字詞中,該元素就會被刪除,除非該名稱存在於白名單之中。

而 purgecss-webpack-plugin 的白名單分為三種,用 safelist 欄位來設定,這三種會被同時使用。

首先是 standard,這個是很單純的名稱對應。例如:

{
    standard: ["example"],
    deep: [],
    greedy: [],
}

若輸入的 CSS 為:

.example {
    width: 100%;
}

.example p {
    font-size: 15px;
}

#example {
    width: 100%;
}

.example-2 {
    width: 100%;
}

經過白名單的檢查之後,只會剩下:

.example {
    width: 100%;
}

#example {
    width: 100%;
}

如果將白名單改為:

{
    standard: ["example", "p"],
    deep: [],
    greedy: [],
}

繼續使用以上的例子,最後它被保留的 CSS 元素則為:

.example {
    width: 100%;
}

.example p {
    font-size: 15px;
}

#example {
    width: 100%;
}

再來是第二種白名單 deep,這個也是用來對應名稱,但是可以使用正規表示式來匹配元素名稱,而且匹配成功的名稱之後的其它名稱都不會再被檢查,所以連它的子元素的 CSS 也會被保留下來。例如:

{
    standard: [],
    deep: [/^example/],
    greedy: [],
}

繼續使用同樣的例子,最後例子中所有的 CSS 元素都可以被保留下來。注意這邊連 .example p 也被保留了!因為 .example 被匹配到之後,就不會再去檢查後面的 p 這個名稱。

不過,deep 白名單是從選擇器的第一個名稱開始依序檢查,如果在遇到匹配成功的名稱之前,就先遇到了沒有被使用到的名稱,整個選擇器還是會被刪除。例如 .container .example,若 container 這個名稱並沒有出現在 paths 欄位所指到的檔案中,即便 example 可以被 deep 白名單匹配到,這個選擇器也還是會被刪除。

如果想要讓 .container .example 也被保留下來,可以使用第三種白名單 greedy,只要選擇器中有任何一個名稱被這個白名單的正規表示式匹配成功,整個選擇器就會被保留下來。

HTML 網頁

Webpack 的 HTML 網頁大致上可以分為兩種,一種是將主要的 CSS 語法甚至是 HTML 語法都寫進 JavaScript 中,而 HTML 檔案內只有撰寫如下的內容:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Title</title>
        <!-- 可能會有簡單的CSS -->
    </head>
    <body>
        <!-- 可能會有讀取畫面 -->
        <script type="text/javascript" src="./path/to/bundle.min.js"></script>
    </body>
</html>

當網頁瀏覽器開啟這個 HTML 網頁時,網頁瀏覽器就會下載 JavaScript 檔案來執行,接著將 HTML 和 CSS 注入到 HTML 網頁中,此時網頁才會顯示出真正的內容。

這種網頁通常會利用大量的 JavaScript 程式來完成畫面的操作流程,讓使用者在操作網頁時不太需要載入新網頁,但這種網頁在開啟的時候通常會有一個等待時間。這部份的用法可以參考這篇文章:

這篇文章要介紹的是第二種的網頁,就是傳統將 HTML 語法直接寫在 HTML 檔案內的作法。例如:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Title</title>
        <script type="text/javascript" src="./path/to/bundle.min.js"></script>
        <link href="./path/to/bundle.min.css" rel="stylesheet">
    </head>
    <body>
        <main class="container">
            <h1 class="mt-5">歡迎</h1>
            <p class="lead">這是我用Webpack做的第一個網頁。</p>
            <p>如果你也有興趣的話可以瀏覽<a href="https://magiclen.org/webpack/">這篇文章</a>。</p>
        </main>
    
        <footer class="footer">
            <div class="container">
                <span class="text-muted">沒有著作權,歡迎分享</span>
            </div>
        </footer>
    </body>
</html>

其實這種網頁,HTML 的部份也不太需要用 Webpack 來打包,不過放進 Webpack 框架中有個最大的好處,那就是可以讓它被最小化!

最小化 HTML 網頁

html-webpack-plugin 外掛可以幫助我們產生 HTML 檔案(如剛才提到的第一種網頁),或是將現有的 HTML 檔案最小化。可以在終端機執行以下指令來安裝這個套件:

npm i -D html-webpack-plugin

在 webpack.config.cjs 設定檔中,將 html-webpack-plugin 的實體加進 plugins 欄位的陣列中,有幾個 HTML 檔案就加幾個 html-webpack-plugin 的實體。

如下:

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    ...

    plugins: [
        ...

        new HtmlWebpackPlugin({
            template: "./path/to/original-html-file",
            filename: "./path/to/output-html-file",
            minify: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true,
                removeEmptyAttributes: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true,
                minifyCSS: true,
                minifyJS: true,
                sortAttributes: true,
                useShortDoctype: true,
            },
            inject: false,
        }),

        ...
    ]

    ...
};

filename 欄位用來設定 HTML 檔案的輸出路徑,其設定方式和 JS 檔案的 filename 是一樣的。

如此一來,經過 Webpack 打包後就會得到最小化的 HTML 檔案。

把 HTML 檔案當作進入點來用

事實上有個 html-loader 載入器,它可以去解析 HTML 中有連結用到的靜態資源網址,並且如 css-loader 載入器一樣可以做到取代網址的動作。換句話說,利用它可以使 HTML 檔案也能夠作為進入點,去打包其有用到的靜態檔案。不過這個載入器的問題有點多,不去用它還比較省時間。

舉一些例子來說明常見問題

關於 libraryTarget

現在 Node.js 專案中有以下幾個檔案。

export function greet(name) {
    alert(`Hello, ${name}!`);
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Greeting</title>
        <script src="./js/bundle.min.js"></script>
    </head>
    <body>
        You should see an alert message.
    
        <script>
            greet("Webpack");
        </script>
    </body>
</html>
const TerserPlugin = require("terser-webpack-plugin");
	 
const HtmlWebpackPlugin = require("html-webpack-plugin");
 
module.exports = {
    output: {
        clean: true,
        filename: "./js/bundle.min.js",
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./views/index.html",
            filename: "./index.html",
            minify: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true,
                removeEmptyAttributes: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true,
                minifyCSS: true,
                minifyJS: true,
                sortAttributes: true,
                useShortDoctype: true,
            },
            inject: false,
        }),
    ],
    module: {
        rules: [
            {
                test: /\.js$/iu,
                use: {
                    loader: "babel-loader",
                    options: { presets: ["@babel/preset-env"] },
                },
            },
        ],
    },
    optimization: {
        minimizer: [
            new TerserPlugin({
                extractComments: false,
                terserOptions: { format: { comments: false } },
            }),
        ]
    },
};

記得用以下指令安裝所需的套件:

npm i -D webpack webpack-cli babel-loader @babel/core @babel/register @babel/preset-env html-webpack-plugin terser-webpack-plugin

在執行 npm run build:webpack 之後,用網頁瀏覽器開啟 dist/index.html。我們預期會看到一個對話框,上面寫著 Hello, Webpack!,然而實際上並沒有,而且網頁瀏覽器的主控台(console)還跳出錯誤訊息,說是 greet 函數沒有定義。

這個其實是因為我們在 webpack.config.cjs 的 output 欄位中,並沒有去設定 library 欄位的值,如果我們將 library 欄位的值設為 lib,如下:

module.exports = {
    ...

    output: {
        ...

        library: "lib",

        ...
    }

    ...
};

就可以將 HTML 語法改成以下這樣來呼叫到 greet 函數。

...

    <body>
        ...
    
        <script>
            lib.greet("Webpack");
        </script>
    </body>

...

為什麼會這樣?這是因為若我們沒有在 webpack.config.cjs 的 output 欄位中設定 libraryTarget 欄位的值,這個值預設為 var,在 var 模式下,用來設定全域變數的 library 欄位的值若沒有設定,就無法正常使用了,因為沒有一個 JS 全域變數有儲存到我們的 JS 模組。

如果要將我們的 JS 模組指派給網頁瀏覽器下的 window 物件來儲存的話,可以將 libraryTarget 欄位的值改為 window,此時的 library 欄位的值就代表我們的 JS 模組會存在 window 物件的哪個欄位。例如:

module.exports = {
    ...

    output: {
        ...

        libraryTarget: "window",
        library: "lib"

        ...
    }

    ...
};
...

    <body>
        ...
    
        <script>
            window.lib.greet("Webpack");
        </script>
    </body>

...

不過由於網頁中的 JavaScript 會自動去看沒有被定義的變數是否是 window 物件的屬性,所以 HTML 中的 JS 程式其實也可以寫成最一開始的模樣:

...

    <body>
        ...
    
        <script>
            lib.greet("Webpack");
        </script>
    </body>

...

若 libraryTarget 欄位的值為 window,但沒有設定 library 欄位的值的話,我們的 JS 模組內有被暴露(export)的項目會被塞給 window 物件。如此一來就可以直接在網頁中呼叫 greet 函數了!

...

    <body>
        ...
    
        <script>
            greet("Webpack");
        </script>
    </body>

...

不過最多人喜歡使用的 libraryTarget 欄位值應該是 umd,它除了有支援 root( 即 window 或 global,要看 webpack.config.cjs 的 target 是設為 Node.js 還是網頁瀏覽器,預設為 web,即網頁瀏覽器)外,還支援 AMD(Asynchronous Module Definition,用 define 來引用模組;用 return 來暴露)、CommonJS(用 require 來引用模組;用 module.exports 或 exports 來暴露)等 JS 模組化的機制。

如果 library 欄位值為 lib,它的 JS 輸出格式會像是這樣:

(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object') // CommonJS
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)           // AMD
		define([], factory);
	else if(typeof exports === 'object')                          // CommonJS
		exports["lib"] = factory();
	else                                                          // root
		root["lib"] = factory();
})(window /* or global */, ...);

如果 library 欄位沒有設定,它的 JS 輸出格式會像是這樣:

(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object') // CommonJS
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)           // AMD
		define([], factory);
	else {                                                        // root
		var a = factory();
		for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
	}
})(window /* or global */, ...);

在 Webpack 中用 Vue.js

Vue.js 是一個非常方便、可在前端或後端運作的框架兼模板引擎。

現在 Node.js 專案中有以下幾個檔案。

import * as Vue from "vue";
	 
const main = {
    data() {
        return { message: "Hello, Webpack!" };
    },
    mounted() {
        alert("Mounted!");
    },
};

export function init() {
    Vue.createApp(main).mount("#main");
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Greeting</title>
        <script src="./js/bundle.min.js"></script>
    </head>
    <body>
        <div id="main">
            {{message}}
        </div>

        <script>
            init();
        </script>
    </body>
</html>
const TerserPlugin = require("terser-webpack-plugin");

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    output: {
        clean: true,
        filename: "./js/bundle.min.js",
        libraryTarget: "window",
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./views/index.html",
            filename: "./index.html",
            minify: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true,
                removeEmptyAttributes: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true,
                minifyCSS: true,
                minifyJS: true,
                sortAttributes: true,
                useShortDoctype: true,
            },
            inject: false,
        }),
    ],
    module: {
        rules: [
            {
                test: /\.js$/iu,
                use: {
                    loader: "babel-loader",
                    options: { presets: ["@babel/preset-env"] },
                },
            },
        ],
    },
    optimization: {
        minimizer: [
            new TerserPlugin({
                extractComments: false,
                terserOptions: { format: { comments: false } },
            }),
        ]
    },
};

記得用以下指令安裝所需的套件:

npm i -D webpack webpack-cli babel-loader @babel/core @babel/register @babel/preset-env html-webpack-plugin terser-webpack-plugin

也記得要安裝 Vue.js:

npm i vue

在執行 npm run build:webpack 之後,用網頁瀏覽器開啟 dist/index.html。我們會看到一個對話框,上面寫著 Mounted!。

用 Webpack 打包 Font Awesome

Font Awesome 是非常多人用的 Icon Font,但是它在 Webpack 下使用時有個地方需要注意,否則無法正常打包。

現在 Node.js 專案中有以下幾個檔案。

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/solid";
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Apple</title>
    <link href="./css/bundle.min.css" rel="stylesheet">
</head>
<body>
    <i class="fas fa-apple-alt fa-10x"></i>
</body>
</html>
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: "./src/index.scss",
    output: {
        clean: true,
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./views/index.html",
            filename: "./index.html",
            minify: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true,
                removeEmptyAttributes: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true,
                minifyCSS: true,
                minifyJS: true,
                sortAttributes: true,
                useShortDoctype: true,
            },
            inject: false,
        }),
        new MiniCssExtractPlugin({ filename: "./css/bundle.min.css" }),
    ],
    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/i,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require("autoprefixer"),
                                    require("cssnano")({ preset: ["default", { discardComments: { removeAll: true } }] }),
                                ],
                            },
                        },
                    },
                    "sass-loader",
                ],
            },
            {
                test: /\.(eot|woff|woff2|[ot]tf)$/iu,
                type: "asset/resource",
                generator: { filename: "fonts/[name][ext]" },
            },
            {
                test: /.*font.*\.svg$/iu,
                type: "asset/resource",
                generator: { filename: "fonts/[name][ext]" },
            },
        ],
    },
};

記得用以下指令安裝所需的套件:

npm i -D webpack webpack-cli sass-loader sass postcss-loader autoprefixer cssnano css-loader mini-css-extract-plugin html-webpack-plugin

也記得要安裝 Font Awesome:

npm i -D @fortawesome/fontawesome-free

但在執行 npm run build:webpack 時,會出現如下的錯誤訊息:

ModuleNotFoundError: Module not found: Error: Can't resolve '../webfonts/fa-solid-900.woff2'

這個是因為 Sass/SCSS 在使用 @import 關鍵字引用其它 Sass/SCSS 檔案(不包含 CSS 檔案)時,貌似是直接拿目標檔案的內容來取代掉那行 @import 關鍵字,所以如果目標檔案的內容有用到相對路徑就會出問題。解決的方法有兩種,第一種就是改成去 @import CSS 檔案(如果有的話),如下:

@import "~@fortawesome/fontawesome-free/css/fontawesome.css";
@import "~@fortawesome/fontawesome-free/css/solid.css";

第二種就是去設定 Sass/SCSS 中儲存著路徑前綴的變數,以 Font Awesome 來說,這個變數為 $font-path。早期的 Sass/SCSS 可以直接在 @import 外面設定變數去影響 @import 的檔案所使用的變數,但新版的模組機制改用 @use 來引用 Sass/SCSS,有不一樣的變數設定方式,而 fontawesome 在 v7 之後也使用了新的機制囉!所以要改用以下的方式來引用:

@use "~@fortawesome/fontawesome-free/scss/variables" with (
    $font-path: "~@fortawesome/fontawesome-free/webfonts"
);

@use "~@fortawesome/fontawesome-free/scss/fontawesome";
@use "~@fortawesome/fontawesome-free/scss/solid";

改寫之後 npm run build:webpack 就可以正常被執行。用網頁瀏覽器開啟 dist/index.html,就可以看到大大的蘋果圖示。