執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

HTML 和靜態站點

使用 Bun 的打包工具建置靜態站點、落地頁和 web 應用

Bun 的打包工具原生支援 HTML。無需任何設定即可建置靜態站點、落地頁和 Web 應用:將 HTML 檔案交給 Bun,它就會打包該檔案所引用的指令碼、樣式表和資源。

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。

terminal
bun ./index.html
Code
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Press h + Enter to show shortcuts

無需設定時,Bun 的開發伺服器提供:

  • 自動打包 - 打包並提供你的 HTML、JavaScript 和 CSS
  • 多入口支援 - 處理多個 HTML 入口點和 glob 入口點
  • 現代 JavaScript - 預設支援 TypeScript 和 JSX
  • 智慧設定 - 讀取 tsconfig.json 中的路徑、JSX 選項和實驗性裝飾器設定
  • 外掛 - 支援外掛,包括 TailwindCSS
  • ESM 和 CommonJS - 在 JavaScript、TypeScript 和 JSX 檔案中使用 ESM 和 CommonJS
  • CSS 打包與壓縮 - 打包來自 <link> 標籤和 @import 語句的 CSS
  • 資源管理 - 複製並生成雜湊化的影像和資源,同時重寫 JavaScript、CSS 和 HTML 中的資源路徑

單頁應用 (SPA)

當你將一個 .html 檔案傳遞給 Bun 時,Bun 會將其用作所有路徑的回退路由。這適用於使用客戶端路由的單頁應用:

terminal
bun index.html
Code
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Press h + Enter to show shortcuts

你的 React 或其他 SPA 無需任何設定即可執行。像 /about 和 /users/123 這樣的路由會提供同一個 HTML 檔案,因此由你的客戶端路由器處理導航。

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

多頁應用 (MPA)

有些專案有幾個獨立的路由或多個 HTML 檔案作為入口點。要支援多個入口點,可以全部傳給 bun:

terminal
bun ./index.html ./about.html
Text
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
  / ./index.html
  /about ./about.html
Press h + Enter to show shortcuts

這會提供:

  • / 路由對應 index.html
  • /about 路由對應 about.html

萬用字元模式

要指定多個檔案,請使用以 .html 結尾的 glob 模式:

terminal
bun ./**/*.html
Code
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
  / ./index.html
  /about ./about.html
Press h + Enter to show shortcuts

路徑規範化

Bun 根據所有檔案中最長的公共字首選擇基礎路徑。

terminal
bun ./index.html ./about/index.html ./about/foo/index.html
Code
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
  / ./index.html
  /about ./about/index.html
  /about/foo ./about/foo/index.html
Press h + Enter to show shortcuts

JavaScript、TypeScript 和 JSX

Bun 的轉譯器原生支援 JavaScript、TypeScript 和 JSX。請參閱載入器。

ES 模組與 CommonJS

您可以在 JavaScript、TypeScript 和 JSX 檔案中使用 ESM 和 CommonJS。Bun 會自動轉譯並打包它們。

無需預建置或單獨的最佳化步驟。Bun 會同時完成所有這些工作。

請參閱模組解析。

CSS

Bun 的 CSS 解析器也是原生實現的(約 70,000 行 Rust 程式碼)。

它也是一個 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 中引用本地資源

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

Bun 會將 ./logo.png 複製到輸出目錄,並重寫 CSS 檔案中的路徑以包含內容雜湊。

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。Bun 會將從 JavaScript 匯入的所有 CSS 檔案打包到每個入口點對應的單個 CSS 檔案中。如果你從多個 JavaScript 檔案匯入同一個 CSS 檔案,Bun 只會在輸出的 CSS 檔案中包含它一次。

外掛

開發伺服器支援外掛。

Tailwind CSS

要使用 TailwindCSS,安裝 bun-plugin-tailwind 外掛:

terminal
# 或任意 npm 客戶端
bun install --dev bun-plugin-tailwind

然後,將外掛新增到你的 bunfig.toml:

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

然後,在 HTML 中通過 <link> 標籤、CSS 中的 @import,或 JavaScript 中的匯入來引用 TailwindCSS。

index.html
<!-- 在 HTML 中引用 TailwindCSS -->
<link rel="stylesheet" href="tailwindcss" />

內聯環境變數

Bun 可以在建置時將 JavaScript 和 TypeScript 中的 process.env.* 引用替換為其實際值。你可以使用此功能將 API URL 或功能標誌等設定注入前端程式碼。

開發伺服器(執行環境)

使用 bun ./index.html 時,可在 bunfig.toml 中設定 env 選項以內聯環境變數:

bunfig.toml
[serve.static]
env = "PUBLIC_*"  # 僅內聯以 PUBLIC_ 開頭的環境變數(推薦)
# env = "inline"  # 內聯所有環境變數
# env = "disable" # 停用環境變數替換(預設)

然後執行開發伺服器:

terminal
PUBLIC_API_URL=https://api.example.com bun ./index.html

生產建置

建置靜態 HTML 生產版本時,使用 env 選項內聯環境變數:

terminal
# 內聯所有環境變數
bun build ./index.html --outdir=dist --env=inline

# 僅內聯帶指定字首的環境變數(推薦)
bun build ./index.html --outdir=dist --env=PUBLIC_*

範例

給定以下原始檔:

app.ts
const apiUrl = process.env.PUBLIC_API_URL;
console.log(`API URL: ${apiUrl}`);

使用 PUBLIC_API_URL=https://api.example.com 執行:

terminal
PUBLIC_API_URL=https://api.example.com bun build ./index.html --outdir=dist --env=PUBLIC_*

捆綁後的輸出包含:

dist/app.js
const apiUrl = "https://api.example.com";
console.log(`API URL: ${apiUrl}`);

將瀏覽器控制台日誌回顯至終端

Bun 的開發伺服器可以將瀏覽器中的控制台日誌流式傳輸到終端。要啟用此功能,請傳入 --console CLI 標誌。

terminal
bun ./index.html --console
Code
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Press h + Enter to show shortcuts

Bun 會將每次 console.log 或 console.error 呼叫廣播到啟動伺服器的終端,因此瀏覽器錯誤會顯示在執行伺服器的同一位置。這也有助於監視終端輸出的 AI 代理。

在內部,Bun 會複用熱模組替換(HMR)現有的 WebSocket 連線來發送日誌。

在瀏覽器中編輯檔案

Bun 的前端開發伺服器支援 Chrome DevTools 中的自動工作區資料夾,因此你可以從瀏覽器儲存對檔案的編輯。

鍵盤快捷鍵

伺服器執行環境:

  • o + Enter - 在瀏覽器中開啟
  • c + Enter - 清除控制台
  • q + Enter 或 Ctrl+C - 退出伺服器。

生產建置

準備部署時,使用 bun build 建立最佳化的生產包:

terminal
bun build ./index.html --minify --outdir=dist

監聽模式

執行 bun build --watch 以監聽更改並自動重新建置。這非常適合庫開發。

外掛 API

如需進行更多控制,可以通過 JavaScript API 設定打包器,並使用 Bun 內建的 HTMLRewriter 預處理 HTML。

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

  plugins: [
    {
      // 一個將所有 HTML 標籤名改為小寫的外掛
      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 的打包器會自動掃描 HTML 中的 <script> 標籤、<link rel="stylesheet"> 標籤及其他資源並打包
            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> 標籤會被重寫路徑並雜湊

Bun 會根據 HTML 檔案解析所有路徑,因此你可以按照任意方式組織專案。

工作原理

開發伺服器是一個小型封裝層,用於支援 Bun 在 JavaScript 中的 HTML 匯入。

單檔案獨立 HTML

你可以使用 --compile --target=browser 將整個前端打包成一個自包含的單個 .html 檔案,且無需外部相依。Bun 會將所有 JavaScript、CSS 和影像直接內聯到 HTML 中。

terminal
bun build --compile --target=browser ./index.html --outdir=dist

瞭解更多內容請參見單檔案獨立 HTML 文件。

給前端新增後端

要為前端新增後端,請使用 Bun.serve 中的 routes 選項。請參閱全棧文件。