許多包有一個或多個可執行文件(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:node
{ "bin" : { "myapp" : "./cli.js" } }
因此,當你引入myapp時,他建立了一個軟連接到 cli.js文件
So, when you install myapp, it’ll create a symlink from the cli.js script tonpm
/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:json
{ "name": "my-program" , "version": "1.2.5" , "bin": "./path/to/program" }
would be the same as this:app
{ "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!this