Skip to main content

6.Github action publish package to NPM

· 3 min read
chasen

An image from the static

Picture from: details

引出

之前很少自己发包到开源社区而且大多数时间是参与别人的开源项目,一直受益于开源社区。想着自己如果有一些公共的代码也方便别人使用。我就先建了一个小仓库 copyforjs (仓库), 是一个复制到粘贴板的小功能,之前使用别人的库发现兼容性做的不好,并且很复杂。功能简单,只是想借着这个库使用下 github action 自动打包发布到npm,虽然感觉很简单,但是还是中间踩了一些坑。把走过的坑记录一下,也算是一步步的帮自己扫盲。

概览

workflow

name: Public Npm

on:
push:
branches: [ main ]

jobs:
publish:
runs-on: ubuntu-latest

name: 'publish npm'

environment: npm

steps:
- uses: actions/checkout@master

- name: Install and Build
run: |
yarn install
yarn run build

- name: 'Publish to the npm registry'
uses: primer/publish@3.0.0
env:
GITHUB_TOKEN: ${{ secrets.COPY_GITHUB_TOKEN }}
NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
with:
default_branch: 'main'

package.json

{
"name": "copyforjs",
"version": "1.0.6",
"private": false,
"description": "Simple copy for javascript, Compatible with all browsers and mobile browsers",
"main": "./dist/index.js",
"files": [
"dist"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Chasen-Zhang/copyforjs.git"
},
"keywords": [
"copyjs",
"copy.js",
"copy",
"js",
"javascript",
"paste",
"clipboard",
"simpleness"
],
"author": "",
"license": "MIT",
"bugs": {
"url": "https://github.com/Chasen-Zhang/copyforjs/issues"
},
"homepage": "https://github.com/Chasen-Zhang/copyforjs#readme",
"dependencies": {
"typescript": "^4.6.4"
}
}

说明

1、GITHUB_TOKEN: Personal access tokens(PAT) https://github.com/settings/tokens 中配置

2、NPM_AUTH_TOKEN: npm token 在npm网站根据下图配置 (我选择的是Automation, publish 亦可), 拿到的这个token需要在github中在当前项目中点击settings去设置secrets 路径为:对应仓库=》settings=》Secrets=》Actions=》New repository secret

An image from the static

An image from the static

3、json当中需要注意的是: main(入口)和files(需要发布的文件目录)字段。

4、如果你使用的是typescript(tsc --init: 生成tsconfig.json文件), 希望提供声明文件,让使用者有提示。可以在tsconfig.json 中将"declaration"设置为true, 这个能帮你自动生成声明文件。