I have written an NPM package which has its own CLI commands.
Let's name that package as xyz
and imagine it's now avaialable on npmjs.com
So, let's say a user installs this package in his project by running npm install xyz
.
And now he wants to run a CLI command provided by xyz
package on his terminal in his project.
xyz do_this
Can this be done without installing this package globally by user ? Or without any further configuration for the user ?
Here's some part of the package.json
of the xyz package.
{
"name": "xyz",
"version": "1.0.0",
"description": "Description",
"main": "index.js",
"preferGlobal": true,
"bin": "./index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
........
Here's how npm works. When you install a package in the local directory, it installs the executable dependencies files inside node_modules inside the folder with package.json, but if you use --global
, it places it globally where the user has set their path.
For example, when I run npm install http-server
, my executable ends up as ./node_modules/http-server/bin/http-server
but when I install it globally, I have it as node_modules/http-server/bin
The work around for this is, if you want to just run the executable, just execute it inside like so ./node_modules/http-server/bin/http-server
. If you want it as a command, you'll need to have the user add the directory to their Path so when the user enters the command, the computer looks for the command inside that folder.
Here's a guide to adding PATH directories in Linux, you'll just add the directory /pathtofolder/node_modules/http-server/bin/
or whatever your folder is. https://linuxize.com/post/how-to-add-directory-to-path-in-linux/
For example, if I wanted to add http-server
from my local folder to my path, I would run
export PATH="/pathtofolder/node_modules/http-server/bin/:$PATH"
Good luck! Let me know how I can help you!