Bun 預設支援 .jsx
和 .tsx
檔案。Bun 的內部轉譯器在執行前會將 JSX 語法轉換成純粹的 JavaScript。
function Component(props: {message: string}) {
return (
<body>
<h1 style={{color: 'red'}}>{props.message}</h1>
</body>
);
}
console.log(<Component message="Hello world!" />);
設定
Bun 會讀取您的 tsconfig.json
或 jsconfig.json
設定檔,以決定如何在內部執行 JSX 轉換。若要避免使用這兩個設定檔,也可以在 bunfig.toml
中定義下列選項。
會遵循下列編譯器選項。
jsx
JSX 建構會在內部如何轉換成純粹的 JavaScript。下表列出 jsx
的可能值,以及其對下列簡單 JSX 元件的轉譯
<Box width={5}>Hello</Box>
編譯器選項 | 轉譯輸出 |
---|---|
|
|
|
|
|
|
|
|
jsxFactory
注意 — 僅適用於 jsx
為 react
時。
用於表示 JSX 結構的函式名稱。預設值為 "createElement"
。這對於使用不同函式名稱("h"
)的函式庫(如 Preact)很有用。
編譯器選項 | 轉譯輸出 |
---|---|
|
|
jsxFragmentFactory
注意 — 僅適用於 jsx
為 react
時。
用於表示 JSX 片段(例如 <>Hello</>
)的函式名稱;僅適用於 jsx
為 react
時。預設值為 "Fragment"
。
編譯器選項 | 轉譯輸出 |
---|---|
|
|
jsxImportSource
注意 — 僅適用於 jsx
為 react-jsx
或 react-jsxdev
時。
將匯入元件工廠函式(createElement
、jsx
、jsxDEV
等)的模組。預設值為 "react"
。這通常在使用 Preact 等元件函式庫時需要。
編譯器選項 | 轉譯輸出 |
---|---|
|
|
|
|
|
|
JSX pragma
所有這些值都可以使用 pragmas 在每個檔案的基礎上設定。Pragma 是設定特定檔案中編譯器選項的特殊註解。
Pragma | 等效設定 |
---|---|
|
|
|
|
|
|
記錄
Bun 實作了 JSX 的特殊記錄功能,以簡化除錯。給定以下檔案
import { Stack, UserCard } from "./components";
console.log(
<Stack>
<UserCard name="Dom" bio="Street racer and Corona lover" />
<UserCard name="Jakob" bio="Super spy and Dom's secret brother" />
</Stack>
);
Bun 會在記錄時漂亮列印元件樹
Prop punning
Bun 執行時期也支援 JSX 的「prop punning」。這是一種簡寫語法,可用於將變數指定給具有相同名稱的 prop。
function Div(props: {className: string;}) {
const {className} = props;
// without punning
return <div className={className} />;
// with punning
return <div {className} />;
}