编写一个简单的本地npm包

124 阅读1分钟

1.初始化npm包

npm init -y

2.新增一个脚本文件

//index.js
#!/usr/bin/env node
console.log('这是一个本地npm包')

你会发现文件会有这样一行代码#!/usr/bin/env node

这句代码的作用是:是为了解决不同用户的node路径不同的问题,可以让系统动态的去查找node来执行你的脚本文件。

3.在packjson中添加bin

{
  "name": "npm-plugin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bin": {
    "npm-plugin-demo": "./index.js"
  },
  "dependencies": {}
}

4.通过npm link命令变成全局包

npm link

也可以通过npm unlink来取消软链

5.执行这个npm包

npm-plugin-demo

执行npm包