1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Preact で Vite 版 Storybook が動かない問題

Last updated at Posted at 2022-04-02

問題

記事投稿時点では、 Preact のプロジェクトに

npx sb init --builder storybook-builder-vite

で Storybook を入れてもうまく表示されません。その対症療法を書き残しておきます。

@mdx-js/preact のバージョン

.mdx 形式の story を表示するために必要なライブラリ @mdx-js/preact が自動では入らないので、入れる必要があります。

しかも @mdx-js/preact はつい最近メジャーバージョンが変わったようで、最新を入れても動きません。メジャーバージョンが変わる直前のバージョンを入れる必要があります。

npm install --save-dev @mdx-js/preact@1.6.22

Vite の設定

加えて、 @storybook/preact が Vite に対応していないため、 Vite のビルドオプションをこちらで設定してやる必要があります。

storybook-builder-vite を使用している場合、 .storybook/main.jsviteFinal で Vite に渡すオプションを設定することができます。

最小の設定は以下になります。

 module.exports = {
   ...,
+  viteFinal: (config) => ({
+    ...config,
+    esbuild: {
+      jsxFactory: "h",
+      jsxFragment: "Fragment"
+    },
+    resolve: {
+      alias: {
+        "react-dom": "preact/compat",
+        react: "preact/compat"
+      }
+    }
+  })
}

JSX を h, Fragment 関数に変換すること、 React 特有の関数を preact/compact で代用することを指定します。

story ファイルでいちいち import { h } from 'preact'; するのが面倒な場合は、さらに以下の行を追加することで勝手に import してくれます。

       jsxFactory: "h",
       jsxFragment: "Fragment",
+      jsxInject: `import { h, Fragment } from "preact"`
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?