All Articles

Adding autocomplete to npm install

Adding autocomplete to npm install

Every time I have to type this without autocomplete I get really annoyed:

$ npm install some-really-really-long-package-name

I spent a few hours last night and figured it out.

Adding autocomplete

Solutions below are for bash / zsh only (not Windows, sorry).

If you don’t use npm autocompletion yet, add this snippet to your ~/.bashrc:

#!/usr/bin/env bash #adding this to force silly gist highlighting. REMOVE THIS

# BASH standalone npm install autocomplete. Add this to ~/.bashrc file.
_npm_install_completion () {
    local words cword
    if type _get_comp_words_by_ref &>/dev/null; then
      _get_comp_words_by_ref -n = -n @ -w words -i cword
    else
      cword="$COMP_CWORD"
      words=("${COMP_WORDS[@]}")
    fi

	local si="$IFS"

	# if your npm command includes `install` or `i `
	if [[ ${words[@]} =~ 'install' ]] || [[ ${words[@]} =~ 'i ' ]]; then
		local cur=${COMP_WORDS[COMP_CWORD]}

		# supply autocomplete words from `~/.npm`, with $cur being value of current expansion like 'expre'
		COMPREPLY=( $( compgen -W "$(ls ~/.npm )" -- $cur ) )
	fi

	IFS="$si"
}
# bind the above function to `npm` autocompletion
complete -o default -F _npm_install_completion npm
## END BASH npm install autocomplete 

If you use zsh, add this to ~/.zshrc.

#!/usr/bin/env zsh #adding this to force silly gist highlighting. REMOVE THIS

# ZSH standalone npm install autocompletion. Add this to ~/.zshrc file.
_npm_install_completion() {
	local si=$IFS

	# if 'install' or 'i ' is one of the subcommands, then...
	if [[ ${words} =~ 'install' ]] || [[ ${words} =~ 'i ' ]]; then

		# add the result of `ls ~/.npm` (npm cache) as completion options
		compadd -- $(COMP_CWORD=$((CURRENT-1)) \
			COMP_LINE=$BUFFER \
			COMP_POINT=0 \
			ls ~/.npm -- "${words[@]}" \
			2>/dev/null)
	fi

	IFS=$si
}

compdef _npm_install_completion 'npm'
## END ZSH npm install autocompletion

If you already use npm autocompletion, replace your version with this one: https://gist.github.com/jamischarles/1669accda0f057df1769c6c0e932827f

Magic!

How it works

We run `ls ~/.npm` and pass all the results as options to bash/zsh autocompletion for the `npm install` command. ~/.npm is the location of the npm cache. This should contain any packages you’ve installed at some point (Not all of npm.).

Questions, comments, feedback? I’m a bash newb, so any improvements are welcome.