tips chips

日々の作業で出てきた技術メモの切れ端を置いておくページ

server-onlyをimportしたファイルを読み込みとテストが通らない問題の対処法

テストでThis module cannot be imported from a Client Component module.と言われる時の対処法

RSC(React Server Components)を用いる際などに、クライアントから読み込まれると困るファイルに対して server-onlyというモジュールをimportすることで、クライアントからの参照時にエラーを発生させるという手法がある。

Next.jsのドキュメントにも記載がある

Building Your Application: Rendering | Next.js
Learn the differences between Next.js rendering environments, strategies, and runtimes.
https://nextjs.org/docs/getting-started/react-essentials#the-server-only-package

これを読み込んでいるモジュールをimportしたテストを書いたとき、 This module cannot be imported from a Client Component module.と言われてしまった。

vitestを使用していたので vite.config.jsに以下の設定をすることで解決した。

export default defineConfig({ test: { // 設定いろいろ alias: { 'server-only': resolve(__dirname, 'node_modules/server-only/empty.js') } } })

server-only は通常、エラーをthrowする処理が書かれた index.jsを読み込ませてエラーを起こし、サーバーコンテキストからインポートしたときだけ empty.jsを読み込ませることでエラーを発生させないようにしている。( empty.jsは名前の通り何も書かれていないJavaScriptファイル)

そういう仕組みなので、aliasを設定してempty.jsがインポートされるようにすれば解決する。