发布自己的npm包(js项目为例)
目标
新建一个通用的js/ts库,方便各前端项目引用。
可以通过pnpm add ...安装。
在github管理,同时发布在npm库中,公开(私有的要钱)。
步骤
Github新建
新建一个public项目,协议可以用ISC或MIT。
可以加.gitignore,README等。
拉到本地。
git clone git@github.com:YOUR_NAME/your-project.git
cd your-project
本地初始化项目
pnpm init
加入必要的包。
pnpm add -D typescript
创建基本结构,如:
project-name/
 ├─ src/
 │   ├─ utils/
 │   ├─ types.ts
 │   └─ C.ts
 ├─ package.json
 ├─ tsconfig.json
 └─ README.md
然后编写代码、测试。
关键代码和配置
package.json:
{
  "name": "project-name",
  "version": "0.1.0",
  "description": "A TypeScript utility library for web, Node and React Native",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsc -p .",
    "prepublishOnly": "pnpm build"
  },
  "keywords": ["typescript", "utils", "shared"],
  "author": "YOUR_NAME",
  "license": "MIT",
  "devDependencies": {
    "typescript": "^5.3.0"
  }
}
原则上不要忘了.gitignore和tsconfig.json。
// tsconfig.ts
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "declaration": true,       // 生成类型声明文件
    "outDir": "dist",          // 编译输出目录
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src"]
}
版本管理(git)
- 新增文件
git add . 
git commit -m "Initial commit"
- Github账号配置
# 按照你的实际情况来
git config user.name "Alan Suhe"
git config user.email "you@example.com"
- 推送到 GitHub
git push -u origin main
- 开发过程中,按功能分支管理(可选):
git checkout -b feature/upper-case 
git add . 
git commit -m "Add upper function" 
git push origin feature/upper-case