node包的创建于发布

一、创建npm包

1、创建一个新文件夹并在编辑器中打开

2、在终端窗口中输入npm init --yes,会自动创建出一个package.json的文件

3、在项目根目录下创建src文件夹和index.js文件;在默认的index.js里写一个要导出的函数,这个函数也就是别人的代码里可以import或者require的。

4、src文件中的方法都需要在index.js文件中

module.exports = require('文件路径');

二、发布

1、在npm官网注册账号——https://www.npmjs.com/signup

2、添加账号

npm login

3、发布包

npm publish 

三、出现问题

1、npm不能使用

配置淘宝源

npm config set registry https://registry.npm.taobao.org
npm config set phantomjs_cdnurl https://npm.taobao.org/mirrors/phantomjs
npm config set sass_binary_site https://npm.taobao.org/mirrors/node-sass
npm config get registry

2、报“[no_perms] Private mode enable, only admin can publish this module [no_perms] Private mode enable, only admin can publish this module: ”错

是NPM源的问题,我换成了淘宝的NPM,所以直接换成原先的NPM源即可。
使用cnpm的原因,设置回原本的就可以了
npm config set registry http://registry.npmjs.org
发布完成之后,如果还想回到之前的cnpm,使用下面的命令

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

四、拉取并使用发布的包

npm i 包名称

文件中引用

var test = require('npm-example-luotongzhou')
test.printMsg();

运行node index.js命令

五、版本更新

修改代码后都需要更新版本并上传

npm version patch

npm publish
原文地址:https://www.cnblogs.com/shuiyu/p/11559937.html