3
4

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 5 years have passed since last update.

【Error: Cannot find module 】yarnでグローバルインストールしたモジュールの参照エラーの対処法

Posted at

はじめに

yarnでグローバルインストールしたモジュールをNode.jsで参照しようとした際に、Cannot find moduleエラーに出くわしました。

yarn addで、開発プロジェクト内にモジュールをローカルインストールすると問題ないのだが、グローバルインストールしたモジュールは参照できませんでした。つまり、PATHに問題があるとみて対処しました。

メモよりの投稿です。

環境

OS: MacOS
Pakcage Manager: yarn

エラー

次のように、requirefugaモジュールをグローバル参照しようとした。

hoge.js
const fuga = require('fuga');

nodeコマンドでjsファイルを実行すると、fugaモジュールを見つけられないと怒られる。

❯ node hoge.js
Error: Cannot find module 'fuga'

対処法

1. グローバルなインストールディレクトリを確認

yarn globalから引用すると、

yarn global dir コマンドは、グローバルな node_modules を含むグローバルなインストールディレクトリの出力を表示します。デフォルトでは、~/.config/yarn/global になります。

❯ yarn global dir
/Users/takuyanin/.config/yarn/global 

2. NODEにグローバルなモジュールパスを設定

export NODE_PATH=$HOME/.config/yarn/global/node_modules

もしくは、.zshenvに記述。

3. グローバルなモジュールパスを確認

global.module.pathsに目的パスが含まれていることを、念のために確認。

❯ node
> global.module.paths
[ '/Users/takuyanin/.config/yarn/global/repl/node_modules',
  '/Users/takuyanin/.config/yarn/global/node_modules', 👈パスが確認できる
  '/Users/takuyanin/.config/yarn/node_modules',
  '/Users/takuyanin/.config/node_modules',
  '/Users/takuyanin/node_modules',
  '/Users/node_modules',
  '/node_modules',
  '/Users/takuyanin/.node_modules',
  '/Users/takuyanin/.node_libraries',
  '/Users/takuyanin/.nvm/versions/node/v10.15.3/lib/node' ]
>

おわりに

基本的には、プロジェクト内に直接インストールすると思うが、ふとした拍子にグローバルインストールしたモジュールを参照しようとすると、少しハマったので、簡単にまとめました。

3
4
1

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?