npm包上传下载的命令及例子

npm包上传下载的命令及例子。

新建hello.js
执行:npm init 
执行:npm adduser
(
username:XXX
password:XXX
email:XXX

)
上传:npm publish .
完成上传。
测试下载:
新建一个文件夹,npm init 然后编写index.js文件
var testnpm = require('npm-helloworld/hello.js')
var str = testnpm.sayHello();
console.log("测试结果:"+str)//测试结果:Hello,world,from 

修改包,要加版本,再npm publish .   再下载最新的代码npm install npm-helloworld@1.0.2
npm-helloworld包加了index.js 所以:
//var testnpm = require('npm-helloworld/hello.js')
var testnpm = require('npm-helloworld')
var str = testnpm.sayHello();
console.log("测试结果:"+str)  //测试结果:Hello,world,from 这是来自index.js文件的测试
因为默认都是找index.js 如果不是则带上文件名字和后缀。


编写模块的规范要遵守:
hello.js的例子:
exports.sayHello=function(){
    return "Hello,world,from "
}

npm install npm-helloworld后,引用例子:
var testnpm = require('npm-helloworld/hello.js')
var str = testnpm.sayHello();
console.log("测试结果:"+str)

执行:node index.js

略。

原文地址:https://www.cnblogs.com/wulinzi/p/10385186.html