node.js的模块开发、发布及安装流程

Yi node.js 2023-07-04 256

1、环境要求

node:v16.20.0 npm:9.6.7

2、项目初始化

mkdir hello
cd hello
npm init 

生成了一个 package.json 文件

{
	"name": "hello",
	"description": "A example for write a module",
	"version": "0.0.1",
	"main": "hello.js"
}

3、模块开发

在根目录创建 hello.js 文件

exports.sayHello = function ( name ) {
	console.log( "Hello " + name );
}

4、本地其它项目模拟引用

在项目同目录下创建一个测试项目 test

mkdir test
cd test
npm install ../hello/

运行测试项目 test

$ node
> require('hello').sayHello('world');
Hello world

测试通过 测试项目package.json 文件

{
  "dependencies": {
    "hello": "file:../hello"
  }
}

5、将模块组件发布到npm

1)注册一个npm账号

npm官网(https://www.npmjs.com)

2)切换到npm官方源

查看npm当前源( npm config get registry 或者 npm config list ) 设置为官方源,用来发布npm包( npm config set registry https://registry.npmjs.org/ ) 设置为阿里镜像源(npm config set registry https://registry.npmmirror.com

3)首次需要设置用户名密码绑定npm

npm adduser ( 输入改行密令 会让你绑定自己的账号 按提示输入 ) 邮箱认证( 点击npm官网头像选择账户,点击2FA认证)

4)发布

在项目根目录执行 npm publish

5)过滤文件

在根目录创建 .npmignore文件,将需要过滤的文件在文件中备注

.idea/
node_modules/
.gitignore
tsconfig.json