故事渲染
在 Storybook 中,您的 story 會在一個特定的「預覽」iframe(也稱為 Canvas)中渲染,該 iframe 位於較大的 Storybook 網路應用程式內。預覽的 JavaScript 建置設定由 建構工具 配置控制,但您可能也希望為每個 story 執行一些程式碼,或直接控制渲染的 HTML,以協助您的 story 正確渲染。
為每個 story 執行程式碼
在預覽檔案 (.storybook/preview.js|ts
) 中執行的程式碼會為 Storybook 中的每個 story 執行。這對於設定全域樣式、初始化函式庫,或渲染元件所需的任何其他操作非常有用。
以下是如何使用預覽檔案初始化函式庫的範例,該函式庫必須在元件渲染之前執行
// Replace your-renderer with the renderer you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-renderer';
import { initialize } from '../lib/your-library';
initialize();
const preview: Preview = {
// ...
};
export default preview;
新增至 <head>
如果您需要將額外的元素新增至預覽 iframe 的 head
,例如載入靜態樣式表、字型檔案或類似資源,您可以建立一個名為 .storybook/preview-head.html
的檔案,並新增如下標籤
<!--
Pull in static files served from your Static directory or the internet
Example:
`main.js|ts` is configured with staticDirs: ['../public'] and your font is located in the `fonts`
directory inside your `public` directory
-->
<link rel="preload" href="/fonts/my-font.woff2" />
<!-- Or you can load custom head-tag JavaScript: -->
<script src="https://use.typekit.net/xxxyyy.js"></script>
<script>
try {
Typekit.load();
} catch (e) {}
</script>
Storybook 會將這些標籤注入到預覽 iframe 中,您的元件會在其中渲染,而不是 Storybook 應用程式 UI。
然而,也可以使用在 main.js
檔案中定義的預設配置,以程式化的方式修改預覽 head HTML。請閱讀 預設配置文件 以取得更多資訊。
新增至 <body>
有時,您可能需要將不同的標籤新增至 <body>
。這對於新增一些自訂內容根目錄很有幫助。
您可以透過在 .storybook
目錄中建立一個名為 preview-body.html
的檔案,並新增如下標籤來完成此操作
<div id="custom-root"></div>
如果在您的專案中使用相對尺寸(例如 rem
或 em
),您可以透過在 preview-body.html
中新增 style
標籤來更新基礎 font-size
<style>
html {
font-size: 15px;
}
</style>
Storybook 會將這些標籤注入到預覽 iframe 中,您的元件會在其中渲染,而不是 Storybook 應用程式 UI。
就像您可以自訂預覽 head
HTML 標籤一樣,您也可以按照相同的步驟,使用預設配置自訂預覽 body
。若要取得更多關於如何執行此操作的資訊,請參閱預設配置文件。