基于Gitea搭建本地npm包服务
0x01 创建 Node 项目
-
新建文件夹作为自定义代码包的项目目录
-
使用命令
npm init -y快速搭建 Node 环境 -
使用命令
npm install --save-dev tsup typescript安装打包相关包- tsup 用于构建 npm 包
- typescript 用于构建 npm 包中的类型声明文件 .d.ts
-
修改 package.json
{ "name": "@my/custom-package", "version": "1.0.0", "description": "", "type": "module", "main": "./dist/index.js", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { ".": { "require": "./dist/index.js", "import": "./dist/index.mjs", "types": "./dist/index.d.ts" } }, "files": [ "dist", "README.md" ], "scripts": { "build": "tsup", "dev": "tsup --watch", "prepublishOnly": "npm run build" }, "publishConfig": { "registry": "http://{Gitea 地址}/api/packages/{用户名}/npm/" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "tsup": "^8.5.1", "typescript": "^5.9.3" } } -
在根目录中创建并编辑以下文件:
-
.gitignore:用于 Git 提交时忽略指定文件
node_modules/ dist/ .DS_Store -
tsup.config.js:用于配置 tsup
import { defineConfig } from "tsup"; export default defineConfig({ entry: ["src/index.js"], // 入口文件 format: ["cjs", "esm"], // 同时生成 CommonJS 和 ES Module dts: true, // 自动生成 .d.ts 类型声明文件 (让JS包也有类型提示) splitting: false, // 代码拆分 (库通常不需要) sourcemap: true, // 生成源码映射,方便调试 clean: true, // 每次打包前清空 dist 目录 }); -
jsconfig.json:用于配置项目中的 JavaScript 检查选项(可选)
{ "compilerOptions": { "module": "ES2022", // 或 "ESNext" / "ES2020" "moduleResolution": "node", // 使别名生效 "target": "ES2022", // 按需 "baseUrl": ".", "paths": { "@/*": ["src/*"] } }, "include": ["src/**/*"] } -
src/index.js:上文指定的自定义包入口文件,以下为示例
/** * 一个简单的加法函数 * @param {number} a * @param {number} b */ export const add = (a, b) => { console.log("Running add function from Gitea package!"); return a + b; }; export const sayHello = (name) => `Hello, ${name}!`;
-
-
使用命令
npm run build查看打包效果
0x02 创建 Gitea 权限
Gitea 版本为1.24.2
- 在 Gitea 的“设置”中找到“应用”
- 选择“生成新的令牌”,编辑新的令牌名称(名称可自定义,如
npm-publish) - 令牌权限必须包含“读写 repository”权限
- 点击“生成令牌”后,复制令牌的内容
0x03 注册与发布
-
在本地终端,使用如下命令配置 npm 仓库权限
npm config set {域}:registry=https://{Gitea地址}/api/packages/{用户名}/npm/ npm config set -- '//{Gitea地址}/api/packages/{用户名}/npm/:_authToken' "{令牌}"如
npm config set `@my:registry=https://192.168.1.2:3000/api/packages/username/npm/` '//192.168.1.2:3000/api/packages/username/npm/:_authToken' "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -
在项目中,使用命令
npm run build打包,使用npm publish进行发布
0x04 使用自发布的包
-
在项目中使用命令
npm install @my/custom-package -
在项目文件中加入如下内容:
import { add, sayHello } from '@my/custom-package'; console.log(sayHello('World')); console.log('1 + 2 =', add(1, 2)); -
编译并运行测试
-End-

浙公网安备 33010602011771号