Good way to install exact dependency globally

186 Views Asked by At

For the Node.js world, we can use NVM to switch between Node.js versions, and also switch out which global packages are in scope (in the $PATH).

However, what if I want to ensure that I use typescript version 3.3.334 at the command line? Obviously, I could install that version of typescript to my local project, but if I wanted to avoid a local dependency, how can I use a shell program to use an exact version of typescript at the command line?

I am thinking something like this:

package="[email protected]"
dir="$HOME/.temp/$package";

if [ ! -d "$dir" ]; then
    mkdir -p "$dir"
    (cd "$dir" && npm i "$package")
fi

export PATH="$dir/node_modules/.bin:$PATH"

do_the_original_thing_you_wanted_to_do foo bar
2

There are 2 best solutions below

0
On

I will probably end up writing some shell script or bash function to switch versions of global cli tools easily, this works:

#!/usr/bin/env bash

package="typescript"
version="3.4.1"

dir="$HOME/.npz_temp/$package/$version";

json='{"name":"foo"}'

if [[ ! -f "$dir/success.json" ]]; then

    mkdir -p "$dir"
    (
        cd "$dir" &&
        echo "$json" > "$dir/package.json" &&
        npm install "$package@$version" &&
        echo 'npm install success' > "$dir/success.json"
    )

fi

export PATH="$dir/node_modules/.bin:$PATH"

tsc --version

all you have to do to generify it is have some arguments for the package and version. this technique should work with compiled/native-code packages also, I don't foresee a problem with that.

7
On

Given that npm comes with npx bundled, you simply might want to run TypeScript with npx and specify the desired version number, such as:

$ npx [email protected]

This will download the typescript package in the desired version and run it (and throw it away afterwards). The only downside of this is that the package will be reinstalled over and over again, everytime you run npx.

You can work around this by installing typescript locally: If it is already installed locally, this local copy is being used, which speeds up things, but generally speaking this is the easiest way to ensure on each single call that you get the version you expect (in contrast to a global installation via npm -g [email protected], which might be overwritten by someone else without you even noticing.

However, this is what you explicitly mentioned that you want to avoid it. So, the way described above may the best choice you have.