简体   繁体   中英

Assigning a command to my NPM Package without installing globally

Some NPM packages are installed into a project, you're then able to run them from your project scripts .

An example of this is webpack-dev-server .

Once installed I just have to add:

"dev": "webpack-dev-server"

In my package.json scripts and it will launch webpack-dev-server .

How does this work? The command isn't globally installed, and yet my Node project knows that it's connected to the package that I have installed.

I've only been able to find information about adding my commands to the bin property within my package's package.json , but that won't work unless the package is installed globally.

How do I achieve this? Is there official documentation somewhere that I haven't been able to find?

you got it right, but you are missing tiny thing...

each package can declare a binary. as you said, this is done in the bin property of the package.json

on install, npm will symlink that file into prefix/bin for global installs, or./node_modules/.bin/ for local installs.

this is exactly what webpack-dev-server does. its binary is being installed within ./node_modules/.bin/ .

due to the convention, npm\npx is able to find the binary and execute it.

in your application, you can utilize this behavior; and any package that will be dependent on your package will be able to execute your package binary.

if you want to provide an argument to the run script, do it like so

npm run webpack-dev-server -- --version

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM