前提
Vite × React × TypeScript 構成のアプリであること。
発生したエラー
- shadcn/ui が生成するモジュールへの path を解決できない
- 同一ファイルで component と helper 関数をまとめてエクスポートできない
解決方法
1. shadcn/ui が生成するモジュールへの path を解決できない
Unable to resolve path to module '@/lib/utils'. eslint(import/no-unresolved)
eslint-plugin-import があると発生します。
shadcn/ui 公式のインストール手順 では、Vite や TypeScript コンパイラに対して @/lib/utils への alias を設定しています。
eslint-plugin-import がある場合、ESLint は import をチェックするため、@/lib/utils を解決できずにエラーを吐くようです。
eslint.config.js に以下を追加することで解決します。
ignore に加えるのは乱暴に思えるかもしれませんが、shadcn/ui が生成するファイルなため Lint を走らせる必要がないという判断です。
export default defineConfig([
// ...
{
files: ['**/*.{js,ts,tsx}'],
// ...
rules: {
// ...
'import/no-unresolved': [
'error',
{
ignore: [
// ...
+ '@/lib/utils',
],
},
],
},
},
// ...
]);
2. 同一ファイルで component と helper 関数をまとめてエクスポートできない
Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components. eslint(react-refresh/only-export-components)
React の Fast Refresh は、状態を保持したままコンポーネントを更新する仕組み です。
React のリポジトリ では、次のように説明されています。
Fast Refresh is a feature that lets you edit React components in a running application without losing their state. It is similar to an old feature known as "hot reloading", but Fast Refresh is more reliable and officially supported by React.
また、Next.js のドキュメント には、次のように書かれています。
React コンポーネント以外のエクスポートを含むファイルを編集した場合、Fast Refresh はそのファイルとそれをインポートする他のファイルを再実行します。例えば、
Button.jsとModal.jsの両方がtheme.jsをインポートしている場合、theme.jsを編集すると両方のコンポーネントが更新されます。
Fast Refresh はファイルごとに効くため、頻繁に更新しない shadcn/ui が生成したファイルのみ react-refresh/only-export-components を OFF にします。
shadcn/ui が生成したファイルで Fast Refresh が効かなくても、開発体験に影響はないだろうという判断です。
export default defineConfig([
// ...
{
files: ['**/*.{js,ts,tsx}'],
// ...
rules: {
// ...
'import/no-unresolved': [
'error',
{
ignore: [
// ...
'@/lib/utils',
],
},
],
},
},
+ {
+ files: ['src/components/ui/**/*.{ts,tsx}'],
+ rules: {
+ 'react-refresh/only-export-components': 'off',
+ },
+ },
]);