Next.jsアプリのStoryBookのビルドをWebpackからViteに置き換える

StoryBookのビルドをWebpackからViteに置き換えてみる。
Next.js製の個人ブログで利用: https://github.com/MH4GF/log.mh4gf.dev
モチベーションはHMRのスピードが上がるといいな程度。

StoryBookの導入から始める場合は npx sb init --builder @storybook/builder-vite
で始められるようだが、既に導入済みの状態で実行しても .storybook/main.js
があるからかスキップされてしまった。
そのため手動で yarn add -D "storybook-builder-vite@*"
を実行する。
viteがないと怒られたので yarn add -D "vite@*"
も実行。
そしてビルダーを 'storybook-builder-vite'
に置き換える。
この時点でWebpackFinalで追加しているWebpackの設定は不要になることが予想されるが、一旦後回し。

ビルドを試してみると以下のようなエラーが出た。
[rollup-plugin-dynamic-import-variables] Unexpected token (8:20)
file: /home/runner/work/log.mh4gf.dev/log.mh4gf.dev/.storybook/preview.js:8:20
ref: https://github.com/MH4GF/log.mh4gf.dev/runs/6139341449?check_suite_focus=true
これは…next/imageをStoryBookで表示するためのワークアラウンドのやつだ コミット
JSXなのに拡張子がjsなのがよくなさそう?と思いjsxに直してみると解消された。(別のエラーは出る)
https://github.com/MH4GF/log.mh4gf.dev/pull/60/commits/52b9dfb3ffe4698c85aed3588bd92b2132f3bd9d

次は以下のようなエラーが出た。
[vite]: Rollup failed to resolve import "~/src/model/ArticleModel" from "src/components/Article/index.stories.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
ERR! Error: [vite]: Rollup failed to resolve import "~/src/model/ArticleModel" from "src/components/Article/index.stories.tsx".
ref: https://github.com/MH4GF/log.mh4gf.dev/runs/6139371425?check_suite_focus=true
importが解決できないとのことなので、 ~
から始まるpathの問題か?

viteの設定をやるのは初めてだが、viteにもwebpackと同じように resolve.alias
の設定があったので追加してみると、これでビルドが通った。

しかしChromaticへのPublishでエラーになってしまう。
✖ Failed to verify your Storybook
Error communicating with the Chromatic API. Check if your Chromatic client is up-to-date.
In case of an outage, we provide status updates at https://twitter.com/chromaui
Check http://status.chromatic.com for service uptime.
→ INTERNAL_SERVER_ERROR: JavaScript failed to load at https://624991c239d2ba004adeffdf-phakhuihxt.capture.chromatic.com/iframe.html
ref: https://github.com/MH4GF/log.mh4gf.dev/runs/6140101847?check_suite_focus=true
/iframe.html
が開けないっぽいな
ローカルで npx http-server storybook-static
を実行して、ビルド結果を立ち上げてみても同様のエラーが出る
Uncaught TypeError: Cannot redefine property: default
at Function.defineProperty (<anonymous>)
at preview.jsx:6:8

これはviteとは関係なく、タイミング悪くStoryBook6.4.22から壊れているとのことだった。以下のIssueでワークアラウンドが紹介されていた。
以下のように修正し解決できた。
https://github.com/MH4GF/log.mh4gf.dev/pull/60/commits/85aa1dbb0f039ad1b2a15f39628bfa75349a56f6

ビルドは通るようになったが、いくつかのコンポーネントが開けなくなっているようだ…なんで…
Reactのproduction buildなのでエラーはこのページで確認することになる
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
:thinking:

これはビルダーをWebpackに戻して yarn build-storybook && npx http-server storybook-static
をすると問題なく開けるので、viteの設定の問題だなあ

このissueが関連しそうでまだ解決はされていないようだ。
rollup側でPRが出ておりApprovedになっているので、ちょっと待ってみるかなあ