Search code examples
node.jspackagenpm

Install a locally developed npm package globally


I'm developing a node package that needs to be run from shell. I know I have to install the package globally, but running

$> npm install -g ./my_module

Does not give me the desired result, that is running

$> my_module

Results in

my_module: : command not found

Instead of running the entry point (index.js) of my node package.

I feel like I'm missing something obvious in here, what am I doing wrong?


Solution

  • After setting up the right package.json configuration, (mainly using {"bin": {...}}), You don't have to publish it to NPM registry then download it again to see it working.

    npm link made exactly for this situations. as described in the offical documentation:

    npm link in a package folder will create a symlink in the global folder {prefix}/lib/node_modules/ that links to the package where the npm link command was executed.

    Assuming you have this project:

    -- my_module
    
    -- -- index.js
    -- -- cli.js
    -- -- package.json
    

    and you have this package.json:

    {
      "name": "my_module",
      "bin": {
        "my_module": "cli.js"
      },
    }
    

    Run:

    cd my_module
    

    Then:

    npm link
    

    Now npm will install your package globally in your machine. it will check the package.json for the bin entry, and it will link my_module to the cli.js file. This will happen by creating a symlink in the global npm directory to your current directory.

    now if you run in your command line:

    my_module
    

    it will point to the cli.js file. if you changed cli.js contents, it will be reflected the next time you run my_module, if you renamed my_module to my_module2, use npm unlink then npm link again.


    On a different note, npm can use a full url as a package name, it will use the full url to download and install the package instead of looking at the npm registry, you can install packages from your own private Git hosts, for example:

    npm install -g https://github.com/Me/my_module