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

	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 ) )

# 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)) \
			ls ~/.npm -- "${words[@]}" \


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

If you already use npm autocompletion, replace your version with this one:


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.

Published 27 May 2016