发布并使用自己的npm包

578 阅读2分钟

一.准备工作

1.npm官网注册账号

npm官网www.npmjs.com/ 注册自己的账户信息

截屏2022-07-29 上午9.52.37.png

2.将自己的镜像源切换到官方源地址
npm config get registry

npm config set registry https://registry.npmjs.org/

截屏2022-07-29 上午10.01.52.png

二.发布

1.登录账户
npm login

截屏2022-07-29 上午10.16.48.png

2.初始化包项目

创建一个新的github仓库test_npm_loso_1

截屏2022-07-29 上午10.26.57.png

本地创建文件夹test_npm_loso_1,并初始化文件

npm init

截屏2022-07-29 上午11.43.04.png

git init

截屏2022-07-29 上午11.44.36.png

根目录下添加LICENSE文件

截屏2022-07-29 上午10.48.58.png

将package.json文件的license字段值由"ISC"修改为"MIT"

 "license": "MIT"
The MIT License (MIT)

Copyright (c) 2022 yangmei

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

根据初始化文件入口创建文件

截屏2022-07-29 上午10.54.46.png

3.编写包的内容

在入口文件中写需要暴露的函数

截屏2022-07-29 上午10.45.16.png

添加到git仓库中

git remote add origin https://github.com/Jz-333/test_npm_loso_1.git

git add .

git commit -m '初始化npm包'

git push --set-upstream origin master
4.推送到npm
npm publish

截屏2022-07-29 上午11.01.48.png

三.使用

1.创建基础项目

创建文件夹test_npm_1,并初始化文件

npm init

添加入口文件

截屏2022-07-29 上午11.10.09.png

2.下载自己发布的包
npm i test_npm_loso_1

截屏2022-07-29 上午11.12.15.png

3.使用npm包

截屏2022-07-29 上午11.14.55.png

截屏2022-07-29 上午11.16.37.png

四.更新版本

1.修改文件内容,并上传到git仓库

截屏2022-07-29 上午11.23.28.png

2.更新版本
npm version major

npm version后面参数说明:

   patch:修复bug  v1.0.0->v1.0.1

   minor:增加新功能,不影响现有功能  v1.0.0->v1.1.0

   major:破坏模块  v1.0.0->v2.0.0

截屏2022-07-29 上午11.24.59.png

3.重新发版
npm publish

截屏2022-07-29 上午11.25.30.png

4.使用最新的版本
npm i test_npm_loso_1@2
更新npm包: 

        patch: npm i test_npm_loso_1
        
        minor: npm i test_npm_loso_1
        
        major: npm i test_npm_loso_1@2.0.0

截屏2022-07-29 上午11.29.57.png