如果希望发的npm包能以全局命令的方式执行,例如像create-react-app vue-cli之类的工具,这些包通常都是安装到全局的,且需要配置bin属性以标识可执行文件的目录
而且bin对应的文件头部第一行应该注明:
#!/usr/bin/env node
以create-react-app为例,其package.json如下:
{
"_from": "create-react-app",
"_id": "create-react-app@2.1.3",
"_inBundle": false,
"_integrity": "sha512-bGx6vYVEZL39QZVP46u4HOh3gazqOcyW/dLWXFNRdmaiL7MBxObo0H3oxkK/YzBqFUvJ++EgncWarQr2PnEK+w==",
"_location": "/create-react-app",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "create-react-app",
"name": "create-react-app",
"escapedName": "create-react-app",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/create-react-app/-/create-react-app-2.1.3.tgz",
"_shasum": "e111a8970a75f9251861e084f31fed10a0ad75e3",
"_spec": "create-react-app",
"_where": "/Users/muyingjie/gitProject/react-study",
"bin": {
"create-react-app": "./index.js"
},
"bugs": {
"url": "https://github.com/facebook/create-react-app/issues"
},
"bundleDependencies": false,
"dependencies": {
"chalk": "1.1.3",
"commander": "2.18.0",
"cross-spawn": "4.0.2",
"envinfo": "5.11.1",
"fs-extra": "5.0.0",
"hyperquest": "2.1.3",
"semver": "5.5.1",
"tar-pack": "3.4.1",
"tmp": "0.0.33",
"validate-npm-package-name": "3.0.0"
},
"deprecated": false,
"description": "Create React apps with no build configuration.",
"engines": {
"node": ">=4"
},
"files": [
"index.js",
"createReactApp.js",
"yarn.lock.cached"
],
"homepage": "https://github.com/facebook/create-react-app#readme",
"keywords": [
"react"
],
"license": "MIT",
"name": "create-react-app",
"repository": {
"type": "git",
"url": "git+https://github.com/facebook/create-react-app.git"
},
"version": "2.1.3"
}
在开发npm包时,为了测试方便,通常会在npm包这个项目的开发目录下执行npm link,从而将当前目录链到npm下,详细内容可参考:docs.npmjs.com/cli/v9/comm…
如果想要拿到执行命令你给时的参数,可以调用原生api process.argv,详细内容可参考:nodejs.org/dist/latest…
但为了简便,通常都会采用第三方包commander的形式进行解析,文档:www.npmjs.com/package/com…