制作npm包的步骤
注册npm账户
1
2npm adduser
或者登陆npm官网注册
登陆npm账户
1
2npm login
编写npm包
- 初始化package.json并配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25npm init
``````json
{
"name": "包名",
"version": "版本号",
"description": "描述",
"main": "入口文件",
"scripts": {
"test": "配置测试"
},
// 配置git仓库
"repository": {
"type": "git",
"url": "git仓库地址"
},
"keywords": [
"关键字"
],
"author": "",
"license": "MIT",
"dependencies": {
}
}发布
1
2
3
4npm publish
# 指定标签beta
npm publish --tag beta删除
1
2npm unpublish --force 包名
命令行工具包的制作
1
2
3
4
5
6
7
8
9
10
11{
"name": "工具名称",
"version": "版本号",
"description": "描述",
"bin": {
"命令名称": "命令入口文件"
},
"author": "zengyuwen",
"license": "MIT"
}代码编写
1
2
3
4
// 获取命令行参数
const arguments = process.argv.splice(2);
代码示例
命令行工具
package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15{
"name": "cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"bin": {
"my-cli": "./index.js"
},
"author": "",
"license": "ISC"
}index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 获取命令行参数
const arguments = process.argv.splice(2);
// 参数解析成数组
function parse(arguments) {
return arguments.map(function(value) {
if (/^-+/.test(value)) {
return value.replace(/^-+/, '');
}
return value;
});
}
// 参数解析成键值对
function parseObj(arguments) {
let result = [];
for (let i = 0;i < arguments.length; i+= 2) {
tmp = {};
if ((i + 1) >= arguments.length) {
tmp[arguments[i].replace(/^-+/, '')] = null;
} else {
tmp[arguments[i].replace(/^-+/, '')] = arguments[i+1];
}
result.push(tmp);
}
return result;
}
// 求和
function add(arguments) {
var params = parse(arguments);
var result = 0;
for (let i of params) {
if (/^[0-9]{1,}$/.test(i)) {
result += parseInt(i);
}
}
return result;
}
console.log(parseObj(arguments));
console.log(add(arguments));