在npm发布第一个包

第一个npm包:web-plus

准备工具

  • 安装node.js
  • 注册一个github账户用于托管代码
  • 注册一个npm账户
  • 开发你的module,更新至github
  • 发布module至npm

    github创建项目

终端进入到项目文件夹,执行npm init命令,构建模块的描述文件,系统会提示你输入所需的信息,不想输入就直接Enter跳过。这里主要的几个配置如下:

  • name就是你要发布的module名
  • version版本信息(每发布一次版本号都必须大于上一次发布的版本号);
  • entry入口文件

开发:

npm init

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
41
42
43
44
45
46
47
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (npm-module) web-plus
version: (1.0.0)
description: 前端常用代码片段
entry point: (index.js)
test command:
git repository: git@github.com:JayMo666/webplus.git
keywords: web
author: JayMo
license: (ISC) MIT
About to write to F:\npm\npm-module\package.json:

{
"name": "web-plus",
"version": "1.0.0",
"description": "前端常用代码片段",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/JayMo666/webplus.git"
},
"keywords": [
"web"
],
"author": "JayMo",
"license": "MIT",
"bugs": {
"url": "https://github.com/JayMo666/webplus/issues"
},
"homepage": "https://github.com/JayMo666/webplus#readme"
}


Is this ok? (yes)

npm注册

npm 命令

1.首先增加用户

npm adduser
如:

1
2
3
4
5
$ npm adduser
Username: jaymo666
Password: *******
Email: (this IS public) 1294****8@qq.com
Logged in as jaymo666 on https://registry.npmjs.org/.

2.查看当前登录用户

npm whoami

3.登录命令(这里已经登录,不用执行此命令)

npm login

开发包-编程

目录结构

  • a.js
  • index.js (这个是入口文件,要和package.json 文件中的 “main”的值一样)
  • package.json (npm init 生成的)

开发

index.js:就开发一个简单地hello程序

1
2
3
4
function hello(name){
console.log("hello "+ name);
}
exports.hello=hello;

b.js

1
2
var h=require('./index');
h.hello('jaymo');

##5.发布npm包

npm publish
进入npm个人中心,可以看到自己的npm包已经发布在上面了

##6.获取npm包

npm install package-name
此处package-name使用web-plus即可
可以看到,多了一个node_modules目录,里面多了一个web-plus文件夹,里面放的就是我们刚才创建的npm包,包含a.js、index.js、package.json三个文件

##7.使用npm包
跟使用普通的npm包一样,问了测试简单,创建一个index.js,输入

1
2
let a = require('web-plus')
a.hello('jaymo')

执行node index即可看见输出了hello jaymo

##8.更新npm包
更新npm包也是使用npm publish命令发布,不过必须更改npm包的版本号,即package.json的version字段,否则会报错
1.查看版本

npm version
2.修改版本
npm version 版本
3.然后发布
npm publish

##9.易出现的错误:

  • 如果在发布的文件下运行a.js文件测试:

node a
如果出现:Cannot find module ‘web-plus’错误,可能是在a文件中require(‘./文件名’);引入出错

  • 如果是使用npm包出现Cannot find module ‘web-plus’错误,可能是:发布的包中package.json文件中main(入口文件)的值不是主文件名(在这里为index.js)

本作品采用 知识共享署名 2.5 中国大陆许可协议 进行许可,欢迎转载,但转载请注明来自JayMo,并保持转载后文章内容的完整。本人保留所有版权相关权利。
本文永久链接:http://jaymo666.github.io/2018/03/14/在npm发布第一个包/