MeWrite Docs

error: Cannot find package or module

Bunでモジュールが見つからない場合のエラー

概要

Bunでパッケージやモジュールが見つからない場合に発生するエラーです。インストール漏れ、パス設定、互換性の問題が主な原因です。

エラーメッセージ

error: Cannot find package "express" imported from /app/src/index.ts
error: Cannot find module "./utils" from "/app/src/index.ts"
error: ModuleNotFoundError: Cannot find package '@types/node'

解決策

1. パッケージをインストール

1
2
bun install express
bun add express  # 同じ意味

2. devDependenciesを含めてインストール

1
2
bun install  # devDependenciesも含む
bun install --production  # productionのみ

3. lockfileを再生成

1
2
rm bun.lockb
bun install

4. node_modulesを再構築

1
2
rm -rf node_modules bun.lockb
bun install

5. パスエイリアスを設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"]
    }
  }
}
1
2
// bunfig.toml (Bun固有の設定)
// Bunはtsconfig.jsonのpathsを自動的に読み取る

6. 相対パスの確認

1
2
3
4
5
6
7
8
// NG: 拡張子が間違っている場合がある
import { utils } from './utils.ts'

// OK: 通常は拡張子なし
import { utils } from './utils'

// OK: Bunは.tsも直接読める
import { utils } from './utils.ts'

7. Node.js互換性の問題

1
2
3
4
// Bunでは一部のNode.js組み込みモジュールの動作が異なる
// node:プレフィックスを使用
import fs from 'node:fs'
import path from 'node:path'

8. グローバルパッケージを使用

1
2
3
4
5
# グローバルにインストール
bun install -g typescript

# グローバルパッケージのパスを確認
bun pm ls -g

9. ワークスペースでの問題

1
2
3
4
// package.json(モノレポ)
{
  "workspaces": ["packages/*", "apps/*"]
}
1
2
3
4
5
# ルートから全パッケージをインストール
bun install

# 特定のワークスペースでコマンド実行
bun run --filter @myapp/web dev

10. キャッシュをクリア

1
2
3
4
5
# Bunのキャッシュをクリア
bun pm cache rm

# グローバルキャッシュの場所
# ~/.bun/install/cache

Node.jsとの互換性

1
2
3
# Node.js用のパッケージで問題がある場合
# --bun フラグでBunランタイムを強制
bunx --bun some-cli-tool

TypeScriptの型定義

1
2
# 型定義をインストール
bun add -d @types/node @types/express

デバッグ方法

1
2
3
4
5
# パッケージの解決パスを確認
bun run --print 'require.resolve("express")'

# 依存関係ツリーを表示
bun pm ls

関連エラー

関連エラー

最終更新: 2025-12-18