how to install npm packages offline

In the rare times when we need npm packages to be installed without internet for development or build environment, I found the following works.

Requirements

  • access to locally hosted git repository (I set up Phabricator for my workplace)
  • access to internet on a machine that can run ‘npm’ command

Steps

On the computer with internet

  • copy out the package.json file to a separate folder, run ‘npm install’ and wait for all the packages to download nicely
  • transfer the folder to a computer that can connect to your internal git repo server
  • if some files failed to copy due to file name too long, we can tar or zip the folder first.

On the computer with access to internal git repo server

  • Create a fresh repository on the local git repo server
  • $ cd node_modules && git init && git add remote origin “your git repo url”
  • $ git config –global core.longpaths true
    • this solves the path too long issue for nested node_modules in Windows
  • $ git push origin master
  • Tada, now you should have all the node modules sitting nicely in a repo to download

On the actual environment that you need the npm packages

  • go to the directory, git clone “your node_modules git repo url”
  • Tada! everything is nicely downloaded now!

.gitignore file

  • To avoid having issues with the .gitignore file, we need to add node_modules/ so the dependencies live as a separate git repo. This will prevent any updates on this one time installed dependencies folder.
  • Also, installing the npm packages outside of the main project and creating a separate npm node_modules repo to host these files will prevent the main project .gitignore from messing up our node_modules repo (i.e. accidentally ignoring some files that comes with npm install without checking them in for dependencies transfer)

Conclusion

Installing npm packages is no longer so straightforward when there is no internet. This solution at least help make our lives easier without frowning at every new fresh installation.

Of course the ultimate solution is to clone a local npm package server. But I heard that’s about 1TB and it’s probably overkill for now.

Yangfan 扬帆 wechat
微信公众号WeChat ID miss_yangfanzhang.