package.json bin的作用

2023-02-12,,,

许多包有一个或多个可执行文件(executable),他们希望直接导入到全局路径里面,这样可以直接使用,npm很容易达到这点,

A lot of packages have one or more executable files that they’d like to install into the PATH. npm makes this pretty easy (in fact, it uses this feature to install the “npm” executable.)

使用这个,在package.json提供一个映射到本地本地文件名的bin字段,一旦被引入后,npm将软链接这个文件到prefix/bin里面,以便于全局引入,或者在./node_modules/.bin/目录里

To use this, supply a bin field in your package.json which is a map of command name to local file name. On install, npm will symlink that file into prefix/bin for global installs, or ./node_modules/.bin/ for local installs.

比如,myapp可能像这样:

For example, myapp could have this:

{ "bin" : { "myapp" : "./cli.js" } }

所以,当你引入myapp时,他创建了一个软链接到 cli.js文件

So, when you install myapp, it’ll create a symlink from the cli.js script to

/usr/local/bin/myapp

如果你有一个单一可执行文件,他的名字应该是和package名字一样,那样你就可以,想使用字符串一样使用它,比如:

If you have a single executable, and its name should be the name of the package, then you can just supply it as a string. For example:

{ "name": "my-program"
, "version": "1.2.5"
, "bin": "./path/to/program" }

would be the same as this:

{ "name": "my-program"
, "version": "1.2.5"
, "bin" : { "my-program" : "./path/to/program" } }

请确保你的bin文件里面最开头写上 #!/usr/bin/env node,否则文件里的脚本不会再Node环境下执行

Please make sure that your file(s) referenced in bin starts with #!/usr/bin/env node, otherwise the scripts are started without the node executable!

package.json bin的作用的相关教程结束。

《package.json bin的作用.doc》

下载本文的Word格式文档,以方便收藏与打印。