新建文件夹(utils)
进入文件夹,运行 npm init 命令,初始化配置项
详细介绍可查看: npm Docs 之 package.json
{
// 包名,必须要独一无二
"name": "utils",
// 版本号 : <主版本号>.<此版本号>.<修订号>-<先行版本号>
"version": "1.0.0-0.1",
// 作者
"author": "xxx",
// 描述信息
"description": "common toolkit",
// 关键词,提升SEO
"keywords": [
"utils",
"format",
"money",
"phone"
],
"repository": {
// 代码托管位置
"type": "git",
"url": "https://github.com/xxx/utils"
},
// 许可证
"license": "ISC",
// 包的主页或者文档首页
"homepage": "https://your-package.org",
// 用户问题反馈地址
"bugs": "https://github.com/xxx/utils/issues",
// 入口文件
"main": "index.js",
"scripts": {
// 存放可执行脚本
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
// 运行依赖
},
"devDependencies": {
// 开发依赖
}
"peerDependencies": {
// 同等依赖,或者叫同伴依赖,用于指定当前包兼容的宿主版本
// 用于解决插件与所依赖包不一致的问题
}
}
完成工具函数文件
import Format from "./src/format";
import Validate from "./src/validate";
export { Format, Validate };
Github 上创建新仓库 utils
按照说明文档,上传项目,并初始化本地分支
git init
git add .
git commit -m "first commit"
git branch -M master
git remote add origin git@github.com:xxx/shang-utils.git
git push -u origin master
在终端中切换到项目目录下,运行登陆命令,之后按照终端提示输入用户名、密码等信息即可
# 登陆
npm login
# 控制台会提示输入相关信息
Log in on https://registry.npmjs.org/
Username: # 用户名
Password: # 密码
Email: (this IS public) # 邮箱
Enter one-time password: # 如果之前做过 双因素身份验证 (2FA),需要生成一次性密钥
Logged in as xxx on https://registry.npmjs.org/.
运行发布命令
# 发布命令
npm publish
发布成功后,就可以登陆 npm 网站,查看发布包的情况了
如果某版本的包有问题,我们还可以将其撤回
npm unpublish [pkg]@[version]
发布哪些文件
package.json/*files 字段*/ > .npmignore > .gitignore
在项目中安装依赖包
npm install utils
使用举例:
// 使用方式
import { Format, Validate } from "utils";
Format.formatMoney(12341234.246, "$", 2); // $12,341,234.25
Validate.mobileCheck("123456"); // false
如下所示:更新了一下说明文档,重新发布
# 自动更改版本号,并且commit
# npm version xxx
# 控制台会返回下一个小版本号 如v1.0.1
npm version patch
# 重新发布
npm publish
# patch:补丁号,修复bug,小变动,如 v1.0.0->v1.0.1
npm version patch
# minor:次版本号,增加新功能,如 v1.0.0->v1.1.0
npm version minor
# major:主版本号,不兼容的修改,如 v1.0.0->v2.0.0
npm version major