Bun

HTML 與靜態網站

Bun 的打包器 (bundler) 具有對 HTML 的一流支援。無需任何設定即可建置靜態網站、到達頁面 (landing page) 和 Web 應用程式。只需將 Bun 指向您的 HTML 檔案,它就會處理所有其他事情。

index.html
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="./styles.css" />
    <script src="./app.ts" type="module"></script>
  </head>
  <body>
    <img src="./logo.png" />
  </body>
</html>

若要開始使用,請將 HTML 檔案傳遞給 bun

bun ./index.html
Bunv1.2.5已就緒,耗時6.62毫秒
https://127.0.0.1:3000/
按下h+Enter顯示快捷鍵

Bun 的開發伺服器提供強大的功能,且無需任何設定。

  • 自動打包 (Bundling) - 打包並提供您的 HTML、JavaScript 和 CSS
  • 多入口支援 (Multi-Entry Support) - 處理多個 HTML 入口點和 glob 入口點
  • 現代 JavaScript - 支援開箱即用的 TypeScript 和 JSX
  • 智慧設定 (Smart Configuration) - 讀取 tsconfig.json 以取得路徑、JSX 選項、實驗性裝飾器 (experimental decorators) 等。
  • 外掛程式 (Plugins) - TailwindCSS 和更多外掛程式
  • ESM 和 CommonJS - 在您的 JavaScript、TypeScript 和 JSX 檔案中使用 ESM 和 CommonJS
  • CSS 打包和最小化 (Minification) - 從 <link> 標籤和 @import 語句打包 CSS
  • 資產管理
    • 自動複製和雜湊 (hashing) 影像和資產
    • 在 JavaScript、CSS 和 HTML 中重寫資產路徑

單頁應用程式 (SPA)

當您將單個 .html 檔案傳遞給 Bun 時,Bun 會將其用作所有路徑的回退路由 (fallback route)。這使其非常適合使用用戶端路由 (client-side routing) 的單頁應用程式。

bun index.html
Bunv1.2.5已就緒,耗時6.62毫秒
https://127.0.0.1:3000/
按下h+Enter顯示快捷鍵

您的 React 或其他 SPA 將可立即運作 — 無需設定。所有路由,例如 /about/users/123 等,都將提供相同的 HTML 檔案,讓您的用戶端路由器處理導航。

index.html
<!doctype html>
<html>
  <head>
    <title>My SPA</title>
    <script src="./app.tsx" type="module"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

多頁應用程式 (MPA)

有些專案有多個獨立的路由或 HTML 檔案作為入口點。若要支援多個入口點,請將它們全部傳遞給 bun

bun ./index.html ./about.html
Bunv1.2.5已就緒,耗時6.62毫秒
https://127.0.0.1:3000/
路由
/./index.html
/about./about.html
按下h+Enter顯示快捷鍵

這將會提供

  • index.html/
  • about.html/about

Glob 模式

若要指定多個檔案,您可以使用以 .html 結尾的 glob 模式。

bun ./**/*.html
Bunv1.2.5已就緒,耗時6.62毫秒
https://127.0.0.1:3000/
路由
/./index.html
/about./about.html
按下h+Enter顯示快捷鍵

路徑正規化

基礎路徑是從所有檔案中最長的共同前綴中選取的。

bun ./index.html ./about/index.html ./about/foo/index.html
Bunv1.2.5已就緒,耗時6.62毫秒
https://127.0.0.1:3000/
路由
/./index.html
/about./about/index.html
/about/foo./about/foo/index.html
按下h+Enter顯示快捷鍵

JavaScript、TypeScript 和 JSX

Bun 的轉譯器原生實作了 JavaScript、TypeScript 和 JSX 支援。深入了解 Bun 中的載入器 (loaders)

Bun 的轉譯器也用於執行階段 (runtime)。

ES Modules 和 CommonJS

您可以在 JavaScript、TypeScript 和 JSX 檔案中使用 ESM 和 CJS。Bun 將自動處理轉譯和打包。

沒有預先建置 (pre-build) 或個別的優化步驟。所有步驟同時完成。

深入了解 Bun 中的模組解析 (module resolution)

CSS

Bun 的 CSS 解析器也是原生實作的(約有 58,000 行 Zig 程式碼)。

它也是一個 CSS 打包器。您可以在 CSS 檔案中使用 @import 來匯入其他 CSS 檔案。

例如

styles.css
@import "./abc.css";

.container {
  background-color: blue;
}
abc.css
body {
  background-color: red;
}

這會輸出

styles.css
body {
  background-color: red;
}

.container {
  background-color: blue;
}

在 CSS 中參考本機資產

您可以在 CSS 檔案中參考本機資產。

styles.css
body {
  background-image: url("./logo.png");
}

這會將 ./logo.png 複製到輸出目錄,並在 CSS 檔案中重寫路徑以包含內容雜湊 (content hash)。

styles.css
body {
  background-image: url("./logo-[ABC123].png");
}

在 JavaScript 中匯入 CSS

若要將 CSS 檔案與 JavaScript 檔案關聯,您可以在 JavaScript 檔案中匯入它。

app.ts
import "./styles.css";
import "./more-styles.css";

這會在輸出目錄中產生 ./app.css./app.js。從 JavaScript 匯入的所有 CSS 檔案都將被打包到每個入口點的單個 CSS 檔案中。如果您從多個 JavaScript 檔案匯入相同的 CSS 檔案,它只會包含在輸出 CSS 檔案中一次。

外掛程式

開發伺服器支援外掛程式。

Tailwind CSS

若要使用 TailwindCSS,請安裝 bun-plugin-tailwind 外掛程式。

# Or any npm client
bun install --dev bun-plugin-tailwind

然後,將外掛程式新增到您的 bunfig.toml

[serve.static]
plugins = ["bun-plugin-tailwind"]

然後,透過 <link> 標籤在 HTML 中、透過 @import 在 CSS 中或透過 import 在 JavaScript 中參考 TailwindCSS。

index.html
styles.css
app.ts
index.html
<!-- Reference TailwindCSS in your HTML -->
<link rel="stylesheet" href="tailwindcss" />
styles.css
/* Import TailwindCSS in your CSS */
@import "tailwindcss";
app.ts
/* Import TailwindCSS in your JavaScript */
import "tailwindcss";

這些方式只需擇一即可,不必全部使用。

鍵盤快捷鍵

當伺服器正在執行時

  • o + Enter - 在瀏覽器中開啟
  • c + Enter - 清除主控台
  • q + Enter (或 Ctrl+C) - 結束伺服器

生產環境建置

當您準備好部署時,請使用 bun build 來建立最佳化的生產環境套件 (production bundles)。

CLI
API
CLI
bun build ./index.html --minify --outdir=dist
API
Bun.build({
  entrypoints: ["./index.html"],
  outdir: "./dist",
  minify: {
    whitespace: true,
    identifiers: true,
    syntax: true,
  }
});

目前,外掛程式僅透過 Bun.build 的 API 或透過前端開發伺服器的 bunfig.toml 支援 - 尚未在 bun build 的 CLI 中支援。

監看模式

您可以執行 bun build --watch 來監看變更並自動重建。這對於程式庫開發非常有用。

您從未見過如此快速的監看模式。

外掛程式 API

需要更多控制權嗎?透過 JavaScript API 設定打包器,並使用 Bun 的內建 HTMLRewriter 來預處理 HTML。

await Bun.build({
  entrypoints: ["./index.html"],
  outdir: "./dist",
  minify: true,

  plugins: [
    {
      // A plugin that makes every HTML tag lowercase
      name: "lowercase-html-plugin",
      setup({ onLoad }) {
        const rewriter = new HTMLRewriter().on("*", {
          element(element) {
            element.tagName = element.tagName.toLowerCase();
          },
          text(element) {
            element.replace(element.text.toLowerCase());
          },
        });

        onLoad({ filter: /\.html$/ }, async args => {
          const html = await Bun.file(args.path).text();

          return {
            // Bun's bundler will scan the HTML for <script> tags, <link rel="stylesheet"> tags, and other assets
            // and bundle them automatically
            contents: rewriter.transform(html),
            loader: "html",
          };
        });
      },
    },
  ],
});

處理了什麼?

Bun 自動處理所有常見的 Web 資產。

  • 腳本 (<script src>) 會透過 Bun 的 JavaScript/TypeScript/JSX 打包器執行。
  • 樣式表 (<link rel="stylesheet">) 會透過 Bun 的 CSS 解析器和打包器執行。
  • 影像 (<img><picture>) 會被複製和雜湊。
  • 媒體 (<video><audio><source>) 會被複製和雜湊。
  • 任何具有指向本機檔案的 href 屬性的 <link> 標籤都會被重寫為新路徑並進行雜湊。

所有路徑都相對於您的 HTML 檔案解析,讓您可以輕鬆地以您想要的任何方式組織您的專案。

這是一個正在進行中的工作

  • 尚無 HMR 支援
  • 需要更多外掛程式
  • 需要更多設定選項來處理資產
  • 需要一種設定 CORS、標頭 (headers) 等的方式。

如果您想提交 PR (Pull Request),大部分程式碼都在這裡。您甚至可以將該檔案複製貼上到您的專案中,並將其用作起點。

運作方式

這是 Bun 在 JavaScript 中對 HTML 匯入支援的一個小型封裝器 (wrapper)。

在您的前端新增後端

若要將後端新增到您的前端,您可以使用 Bun.serve 中的 "routes" 選項。

完整堆疊 (full-stack) 文件中深入了解。