How to create a npm package
2024-07-18

基本步骤

1. 项目初始化

mkdir my-package && cd my-package && npm init # git init # 可选择不执行,添加后k可推送到远端方便远程管理 # 创建 `.gitignore` 文件

2. 编写包

2.1 配置 package.json

{ "name": "my-package", "version": "1.0.0", "description": "A simple npm package example", "main": "index.js", "keywords": ["example", "npm", "package"], "author": "Your Name", "license": "MIT", "files": ["index"], "publishConfig": { "registry": "http://xxx" } }
  1. files 用于指定发布的文件,默认全部发布上去
  2. publishConfig 当我们需要将该包发布到私有服务器的时候,需要指定该值为私有服务器的地址,且下载的时候也需要指定下载 源。

2.2 下载相关依赖

npm i package-name --save-peer # 将该包视为 peerDependencies

3. 发布包

写好之后就可发布了

npm login npm publish

3.1 更新并发布

npm version patch # 1.0.0 --> 1.0.1 适用于向下兼容的错误修复 npm version minor # 1.0.0 --> 1.1.0 适用于向下兼容的新增功能 npm version major # 1.0.0 --> 2.0.0 使用于不向下兼容的更改 npm version 2.1.0 # 指定版本号

可以添加一个脚本来自动化版本号升级

{ "scripts": { "release:patch": "npm version patch && npm publish", "release:minor": "npm version minor && npm publish", "release:major": "npm version major && npm publish" } }
LAST UPDATED:
2024-08-19 00:33:26