Skip to content

Instantly share code, notes, and snippets.

@usergenic
Last active May 6, 2022 13:01
Show Gist options
  • Save usergenic/a7bf86f31145748e9f46a0b35f0eb31f to your computer and use it in GitHub Desktop.
Save usergenic/a7bf86f31145748e9f46a0b35f0eb31f to your computer and use it in GitHub Desktop.
npm link sucks because symlinks and node_modules, so i use this instead
# Given a single argument, being the folder to a local copy of the npm package to "install"
# copy it to the local node_modules folder, then make sure it has no node_modules of its own.
# This way you can npm install locally afterwards to cover remaining dependencies and
# everything will work right.
function npm_import {
export pkgname=`basename $1`
export pkgdir="node_modules/$pkgname"
if [ -d "$pkgdir" ]; then
rm -rf "$pkgdir"
fi
mkdir -p node_modules
cp -r $1 "$pkgdir"
if [ -d "$pkgdir/node_modules" ]; then
rm -rf "$pkgdir/node_modules"
fi
if [ -d "$pkgdir/.git" ]; then
rm -rf "$pkgdir/.git"
fi
}
@usergenic
Copy link
Author

usergenic commented Mar 31, 2017

Usage example (importing a local version of polymer-analyzer into polymer-build-- a common scenario for me)

cd ~/src/github.com/polymer/polymer-build
npm_import ~/src/github.com/polymer/polymer-analyzer

The idea is that the script copies over the target node module into the local node modules folder and then removes its sub-folders. For TypeScript projects in-particular this avoids the dreaded duplicate type definition hell that results from the way npm link works.

Assuming the version number in the imported module matches what's in the project's package.json, subsequent npm install won't override the imported module, so you can run npm install to get any missing dependencies that might otherwise have been removed when the nested node modules folder was deleted by this script upon import.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment