简体   繁体   English

将命令分配给我的 NPM Package 而不全局安装

[英]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 .一些 NPM 包安装到项目中,然后您可以从项目scripts中运行它们。

An example of this is webpack-dev-server .这方面的一个例子是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 .在我的package.json脚本中,它将启动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.该命令未全局安装,但我的 Node 项目知道它已连接到我已安装的 package。

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.我只能在我的包的package.json中找到有关将命令添加到bin属性的信息,但除非全局安装 ZEFE90A8E604A7C840E88D03A67F6B78D,否则这将不起作用。

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.每个 package 都可以声明一个二进制文件。 as you said, this is done in the bin property of the package.json正如你所说,这是在package.jsonbin属性中完成的

on install, npm will symlink that file into prefix/bin for global installs, or./node_modules/.bin/ for local installs.安装时,npm 会将该文件符号链接到前缀/bin 以进行全局安装,或将./node_modules/.bin/ 符号链接到本地安装。

this is exactly what webpack-dev-server does.这正是webpack-dev-server所做的。 its binary is being installed within ./node_modules/.bin/ .它的二进制文件安装在./node_modules/.bin/中。

due to the convention, npm\npx is able to find the binary and execute it.由于约定,npm\npx 能够找到二进制文件并执行它。

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.任何依赖于 package 的 package 都将能够执行 package 二进制文件。

if you want to provide an argument to the run script, do it like so如果您想为运行脚本提供参数,请这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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