如何发布 node 模块到 npm 社区
1. 注册
首先需要注册一个用户:
npm adduser
Username: YOUR_USER_NAME
Password: YOUR_PASSWORD
Email: YOUR_EMAIL@domain.com
也可以NPM 官网注册 成功之后,npm 会把认证信息存储在 ~/.npmrc
中,并且可以通过以下命令查看 npm 当前使用的用户:
npm whoami
如果已经注册过,就使用下面的命令登录:
npm login
需要输入用户名、密码和邮箱。
2. files
在你发布一个 npm 包之前一定要明确项目的哪些文件需要发布,默认 npm 会去读 .npmignore
文件,如果没有就会去读 .gitignore
。一般来说你不用刻意地加入 .npmignore
文件,往往我们需要发布的东西只有dist
, lib
, es
等打包后的东西,所以我们直接在 package.json
里面加入 files
字段声明即可:
// package.json
{
"files": ["dist", "lib", "es", "foo.js"]
}
files
属性的值是一个数组,内容是模块下文件名或者文件夹名,如果是文件夹名,则文件夹下所有的文件也会被包含进来(除非文件被另一些配置排除了)。你也可以在模块根目录下创建一个 .npmignore
文件,写在这个文件里边的文件即便被写在 files
属性里边也会被排除在外,这个文件的写法 .gitignore
类似。
Details
- Entries in
files
are minimatch globs. That means*.js
,lib/**/*.js
, etc, all work. - Entries in
files
are converted to include subdirectories, even ones intended as files. For example, foo.js will be treated as bothfoo.js
andfoo.js/**
. It also meanslib
is all you need in order to include everything in that directory. - A trailing
/
infiles
does nothing. - npm automatically includes and excludes certain files, regardless of your settings. The entire list is in the npm documentation for package.json.
node_modules/
gets special treatment. If you want to include dependencies in your publish, usebundledDependencies
.- "The consequences are undefined" if you try to negate any of the
files
entries (that is,"!foo.js"
). Please don't. Use.npmignore
.
.npmignore
文件的编写规则请参考:https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package
3. 更新包
更新包的话,coding 完了千万不直接发布,这里我们需要修改 package 的 version 号,但这里不要直接修改,修改之前先说下 npm 维护 package 版本的规则 x.y.z
- x: 主版本号,通常有重大改变或者达到里程碑才改变
- y: 次要版本号,或二级版本号,在保证主体功能基本不变的情况下,如果适当增加了新功能可以更新此版本号
- z: 尾版本号或者补丁号,一些小范围的修修补补就可以更新补丁号
npm version patch <=> z++
npm version minor <=> y++ && z=0
npm version major <=> x+= && y=0 && z=0
再执行 npm publish
就是重新发布新的 package。
如果 npm 包同时又是一个 git 仓库,在运行了 npm version <update_type>
和 npm publish
之后,npm 会自动给 git 仓库打上一个跟当前版本号一样的 tag,对于仓库在 github 上的 npm 包会比较有用。
如果你希望项目发布的时候能够自动生成 CHANGELOG.md
文件,可以借助 standard-version 这样的工具, 自动生成 CHANGELOG, 甚至是 语义化的版本号(Semantic Version).
安装:
npm i standard-version
package.json
配置:
"script": {
"release": "standard-version"
}
详细用法请参考 standard-version 文档,结合 commitizen/cz-cli 和 commitizen/cz-conventional-changelog 使用效果更佳。