创建您的第一个 Github 包
Github 自 2019 年 5 月起推出了 Github Package Registry,这是一种包管理服务,类似于 NPM 包。这意味着您可以在源代码旁边管理私有或公共包。
在我撰写本文时,您仍然必须注册测试版才能尝试这项新服务。
以下是创建您的第一个 Github 包可以遵循的步骤。
步骤 1:创建个人访问令牌
登录你的Github 账户 > 设置 > 开发者设置
第二步:登录npm.pkg.github.com
dnguyen:~ dalenguyen$ npm login --registry=https://npm.pkg.github.com
Username: GitHub-username
Password: your-personal-access-token
Email: (this IS public) your-email@example.com
Logged in as dalenguyen on https://npm.pkg.github.com/.
步骤 3:准备源代码
我已经创建了一个 TypeScript 包启动器。你可以从 Github 克隆它。
git clone https://github.com/dalenguyen/typescript-package-starter.git
项目结构如下:
dist
--index.js
src
--index.ts
test
--index.spec.ts
这个包只有一个简单的函数:helloWorld
export const helloWorld = () => 'Howdy!'
为了将你的包发布到 Github 包注册表,你需要添加publishConfig。否则,它会将包发布到 NPM 包注册表。
{
"name": "typescript-package-starter",
"version": "1.0.0",
"description": "TypeScript boilerplate for NPM or Github Packages",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"test": "mocha --timeout 60000 --exit -r ts-node/register test/**/*.spec.ts",
"build": "tsc",
"deploy": "npm publish"
},
"author": "Dale Nguyen",
"license": "ISC",
"repository": {
"type": "git",
"url": "git+https://github.com/dalenguyen/typescript-package-starter.git"
},
.........................
"publishConfig": {
"registry": "https://npm.pkg.github.com/@dalenguyen"
}
}
这将创建一个包名称:@dalenguyen /typescript-package-starter。当你使用自己的包时,需要替换 package.json 中的用户名。
感谢我的同事 Alex,通过添加存储库,您可以将多个包发布到同一个 GitHub 存储库。
步骤 4:将你的项目推送到 Github repo
代码准备好后,将其推送到你的 GitHub 仓库。你需要在 Github.com 创建你的仓库。
git init
git add .
git commit -m "Create first github package"
git push origin master
第六步:发布你的第一个 Github 包
运行测试,确保一切正常
npm test
部署你的第一个 Github 包
npm run build && npm deploy
瞧!
步骤 7:尝试安装你的第一个 Github 包
在此之前,你需要创建一个 .npmrc 文件
// .npmrc
@your-username:registry=https://npm.pkg.github.com
然后安装你的包:
dalenguyen$ npm i @dalenguyen/typescript-package-starter
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN github-packages@1.0.0 No repository field.
+ typescript-package-starter@1.0.0 (as @dalenguyen/typescript-package-starter)
added 1 package from 1 contributor and removed 6 packages in 2.375s
步骤 8:测试新创建的包
// index.js
const starter = require('@dalenguyen/typescript-package-starter')
console.log(starter.helloWorld())
运行index.js文件
dalenguyen$ node index.js
Howdy!
现在你已经知道如何创建并发布你的第一个 Github 包了。在下一篇文章中,我将尝试添加 CI/CD,以便使用 Github Actions 自动发布包。
文章来源:https://dev.to/dalenguyen/create-your-first-github-package-564f