Vagrantの共有ディレクトリでのnpmインストールエラー回避


最初に

vagrantでLaravelの環境を作ることがよくあります。
Laravelプロジェクトを共有ディレクトリに配置し、ローカルで開発。
よくある話かと思います。
※まぁ、Homesteadとかで。

npmインストールエラー

んで、vueを使いたい時もあるわけです。
ですが、vagrantログイン後、Laravelプロジェクト下でnpm installをするとエラーが出ます。

# Vagrantfileの設定
config.vm.synced_folder "./data", "/home/vagrant/project"
# (vagrantログイン後)Laravelプロジェクト直下にて
$ pwd
/home/vagrant/project/SampleProject
$ npm install
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /home/vagrant/project/SampleProject/node_modules/yargs/node_modules/require-main-filename/package.json.2754704624
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/home/vagrant/project/SampleProject/node_modules/yargs/node_modules/require-main-filename/package.json.2754704624'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2020-02-03T07_39_18_468Z-debug.log

上記回避策として、ローカルにて、Laravelプロジェクト下で、npm installを実行、があるようです。他にもあるかと思いますが…

マウントにてエラー回避

ローカルにnodeを入れない(入れたくない!)場合、node_modulesを共有ディレクトリ以外のディレクトリにマウントしてあげるとエラーが回避できるようです。
※正しい回避策かは不明ですが…

$ mkdir /home/vagrant/vagrant_node_modules
$ sudo mount --bind /home/vagrant/vagrant_node_modules /home/vagrant/project/SampleProject/node_modules

参考ページ:Isolating node_modules in Vagrant