福州市网站建设_网站建设公司_会员系统_seo优化
2026/3/3 1:51:07 网站建设 项目流程

0x01 创建 Node 项目

  1. 新建文件夹作为自定义代码包的项目目录

  2. 使用命令 npm init -y 快速搭建 Node 环境

  3. 使用命令 npm install --save-dev tsup typescript 安装打包相关包

    • tsup 用于构建 npm 包
    • typescript 用于构建 npm 包中的类型声明文件 .d.ts
  4. 修改 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"}
    }
  5. 在根目录中创建并编辑以下文件:

    1. .gitignore:用于 Git 提交时忽略指定文件

      node_modules/
      dist/
      .DS_Store
      
    2. tsup.config.js:用于配置 tsup

      import { defineConfig } from "tsup";export default defineConfig({entry: ["src/index.js"], // 入口文件format: ["cjs", "esm"], // 同时生成 CommonJS 和 ES Moduledts: true, // 自动生成 .d.ts 类型声明文件 (让JS包也有类型提示)splitting: false, // 代码拆分 (库通常不需要)sourcemap: true, // 生成源码映射,方便调试clean: true, // 每次打包前清空 dist 目录
      });
    3. jsconfig.json:用于配置项目中的 JavaScript 检查选项(可选)

      {"compilerOptions": {"module": "ES2022", // 或 "ESNext" / "ES2020""moduleResolution": "node", // 使别名生效"target": "ES2022", // 按需"baseUrl": ".","paths": {"@/*": ["src/*"]}},"include": ["src/**/*"]
      }
    4. 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}!`;
  6. 使用命令 npm run build 查看打包效果

0x02 创建 Gitea 权限

Gitea 版本为1.24.2

  1. 在 Gitea 的“设置”中找到“应用”
  2. 选择“生成新的令牌”,编辑新的令牌名称(名称可自定义,如 npm-publish
  3. 令牌权限必须包含“读写 repository”权限
  4. 点击“生成令牌”后,复制令牌的内容

0x03 注册与发布

Gitea 官方文档关于 npm 包注册的指南

  1. 在本地终端,使用如下命令配置 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"
    
  2. 在项目中,使用命令 npm run build 打包,使用 npm publish 进行发布

0x04 使用自发布的包

  1. 在项目中使用命令 npm install @my/custom-package

  2. 在项目文件中加入如下内容:

    import { add, sayHello } from '@my/custom-package';console.log(sayHello('World'));
    console.log('1 + 2 =', add(1, 2));
    
  3. 编译并运行测试

-End-

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询