Tips & Tricks (अपडेट: 2/6/2026)

Claude Code से npm package बनाना और publish करना

Claude Code से npm package बनाएं: tsup, exports, types, npm pack, README और CI publish workflow के साथ।

Claude Code से npm package बनाना और publish करना

Claude Code से “एक npm package बना दो” कहना आसान है। लेकिन ऐसा package publish करना, जिसे दूसरे developers बिना समस्या install कर सकें, अलग काम है। सिर्फ function लिखना काफी नहीं होता। package.json, exports, type declarations, README, npm pack की file list, और CI publish workflow सब साथ में ठीक होने चाहिए।

इस guide में हम TypeScript का छोटा string utility package बनाएंगे। Claude Code को publish button नहीं देंगे; उसे file generate करने, configuration review करने और risk समझाने के लिए इस्तेमाल करेंगे। असली release से पहले npm की official docs देखें: package.json, scoped public packages, npm pack, trusted publishing और Claude Code docs

पहले package contract लिखें

पहला prompt साफ होना चाहिए। package name, user, runtime, module formats, verification commands और publish policy बताएं। type: "module", main, exports और types आपस में जुड़े हैं। एक गलत path होने पर package build हो सकता है, पर user project में import fail हो सकता है।

Areaइस guide का decisionClaude Code से check करवाएं
Name@acme/string-kitscoped public package में --access public चाहिए या नहीं
UsersNode.js और TypeScript usersESM import और CJS require दोनों चलते हैं या नहीं
Buildtsup से ESM, CJS और typesexports जिन files को दिखाता है, वे dist में हैं या नहीं
Contentsकेवल dist, README.md, LICENSEnpm pack --dry-run में extra files तो नहीं
PublishGitHub Actions + npm Trusted Publishinglong-lived npm token से बचा गया या नहीं

Flow पहले दिखा दें तो Claude Code सिर्फ code बनाकर package check भूलता नहीं।

flowchart LR
  A["Package brief"] --> B["package.json"]
  B --> C["src/index.ts"]
  C --> D["Vitest"]
  D --> E["tsup build"]
  E --> F["npm pack dry-run"]
  F --> G["CI publish"]

अगर package CLI बनना है तो Claude Code CLI tool development भी पढ़ें। Prompt और verification habits के लिए Claude Code productivity tips उपयोगी हैं।

Minimal project बनाएं

पहले clean folder में test करें। बड़े repository में workspace config, old dependencies और existing scripts के कारण असली गलती छिप सकती है।

mkdir string-kit
cd string-kit
npm init -y
npm install -D typescript tsup vitest @types/node
mkdir src scripts

package.json public contract है। main CJS users के लिए, module कुछ bundlers के लिए, types TypeScript के लिए और exports modern entry points के लिए है। files छोटा रखने से tests, drafts, sourcemaps और local config publish होने से बचते हैं।

{
  "name": "@acme/string-kit",
  "version": "0.1.0",
  "description": "Small TypeScript string utilities used as an npm package example.",
  "type": "module",
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    },
    "./package.json": "./package.json"
  },
  "files": ["dist", "README.md", "LICENSE"],
  "sideEffects": false,
  "scripts": {
    "build": "tsup",
    "test": "vitest run",
    "docs": "node scripts/write-readme.mjs",
    "test:pack": "npm pack --dry-run",
    "prepublishOnly": "npm run test && npm run build && npm run test:pack"
  },
  "keywords": ["string", "typescript", "utilities"],
  "license": "MIT",
  "devDependencies": {
    "@types/node": "^22.15.0",
    "tsup": "^8.5.0",
    "typescript": "^5.8.0",
    "vitest": "^3.2.0"
  }
}

TypeScript type check करेगा, output tsup बनाएगा। इससे Claude Code आसानी से देख सकता है कि dist और exports match करते हैं या नहीं।

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "declaration": true,
    "declarationMap": true,
    "skipLibCheck": true,
    "noEmit": true
  },
  "include": ["src", "tsup.config.ts"]
}

चलने वाला implementation और tests

Article में pseudo code नहीं होना चाहिए। यह package चार छोटे functions export करता है: slugify, truncate, interpolate, और byteLength। Code छोटा है, लेकिन build, test, types और package verification सब दिखाता है।

export function slugify(input: string): string {
  return input
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export function truncate(input: string, maxLength: number, suffix = "..."): string {
  if (!Number.isInteger(maxLength) || maxLength < 1) {
    throw new RangeError("maxLength must be a positive integer");
  }
  if (suffix.length >= maxLength) {
    throw new RangeError("suffix must be shorter than maxLength");
  }
  if (input.length <= maxLength) return input;
  return `${input.slice(0, maxLength - suffix.length)}${suffix}`;
}

export function interpolate(template: string, values: Record<string, string | number>): string {
  return template.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (match, key: string) => {
    return Object.hasOwn(values, key) ? String(values[key]) : match;
  });
}

export function byteLength(input: string): number {
  return new TextEncoder().encode(input).length;
}

Tests normal case, boundary, error और Unicode check करते हैं। Claude Code से केवल “tests add करो” न कहें; accents, unknown placeholders, invalid lengths और UTF-8 bytes साफ लिखें।

import { describe, expect, it } from "vitest";
import { byteLength, interpolate, slugify, truncate } from "./index";

describe("slugify", () => {
  it("turns a title into an npm-friendly slug", () => {
    expect(slugify("Hello npm Package!")).toBe("hello-npm-package");
  });

  it("removes accents before replacing separators", () => {
    expect(slugify("Crème brûlée utils")).toBe("creme-brulee-utils");
  });
});

describe("truncate", () => {
  it("keeps short text unchanged", () => {
    expect(truncate("short", 10)).toBe("short");
  });

  it("adds a suffix inside the requested length", () => {
    expect(truncate("Claude Code package", 12)).toBe("Claude Co...");
  });

  it("rejects invalid lengths", () => {
    expect(() => truncate("abc", 2)).toThrow(RangeError);
  });
});

describe("interpolate", () => {
  it("replaces known placeholders and keeps unknown ones", () => {
    expect(interpolate("Hi {{ name }}, ship {{pkg}} {{missing}}", {
      name: "Masa",
      pkg: "@acme/string-kit",
    })).toBe("Hi Masa, ship @acme/string-kit {{missing}}");
  });
});

describe("byteLength", () => {
  it("counts UTF-8 bytes", () => {
    expect(byteLength("npm")).toBe(3);
    expect(byteLength("日本語")).toBe(9);
  });
});

tsup और README generator

tsup config छोटा है। outExtension ESM को .js और CJS को .cjs बनाता है। यह package.json entry points से match करता है। sourcemap: false इसलिए है ताकि internal source map अनजाने में publish न हो।

import { defineConfig } from "tsup";

export default defineConfig({
  entry: ["src/index.ts"],
  format: ["esm", "cjs"],
  dts: true,
  clean: true,
  sourcemap: false,
  minify: false,
  target: "es2022",
  outDir: "dist",
  outExtension({ format }) {
    return { js: format === "esm" ? ".js" : ".cjs" };
  },
});

README जल्दी outdated हो सकता है। छोटा generator install और usage examples को API के साथ sync रखता है।

import { writeFile } from "node:fs/promises";

const fence = String.fromCharCode(96).repeat(3);
const readme = `# @acme/string-kit

Small TypeScript string utilities packaged with tsup.

## Install

${fence}bash
npm install @acme/string-kit
${fence}

## Usage

${fence}ts
import { slugify, truncate } from "@acme/string-kit";

console.log(slugify("Hello npm Package!"));
console.log(truncate("Claude Code package", 12));
${fence}
`;

await writeFile(new URL("../README.md", import.meta.url), readme);

npm pack से publish से पहले check करें

npm publish पहली real verification नहीं होनी चाहिए। npm pack --dry-run बताता है कि registry में कौन सी files जाएंगी।

npm run docs
npm test
npm run build
npm pack --dry-run
node -e "import('./dist/index.js').then((m)=>console.log(m.slugify('Hello ESM')))"
node -e "const m=require('./dist/index.cjs'); console.log(m.slugify('Hello CJS'))"

और बेहतर smoke test के लिए generated .tgz को अलग folder में install करें।

npm pack
mkdir ../string-kit-smoke
cd ../string-kit-smoke
npm init -y
npm install ../string-kit/acme-string-kit-0.1.0.tgz
node -e "import('@acme/string-kit').then((m)=>console.log(m.truncate('Claude Code package', 12)))"

तीन real use cases हैं। Product team web, admin और docs में same string rules share कर सकती है। Content workflow descriptions और release notes को consistent बना सकता है। Design system या CLI छोटे utilities को अलग publish कर सकते हैं, ताकि apps SemVer से update करें।

GitHub Actions से publish करें

CI से publish करने पर process reviewable बनता है। npm Trusted Publishing OIDC का उपयोग करता है और long-lived npm token की जरूरत कम करता है। npm में trusted publisher configure करें और publish को release event तक सीमित रखें।

name: package

on:
  push:
    branches: [main]
  pull_request:
  release:
    types: [published]

permissions:
  contents: read
  id-token: write

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          registry-url: https://registry.npmjs.org
          cache: npm
      - run: npm ci
      - run: npm run docs
      - run: npm test
      - run: npm run build
      - run: npm pack --dry-run

  publish:
    if: github.event_name == 'release'
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          registry-url: https://registry.npmjs.org
          cache: npm
      - run: npm ci
      - run: npm run docs
      - run: npm test
      - run: npm run build
      - run: npm publish --access public

Version notes और SemVer के लिए Claude Code और Changesets साथ में उपयोगी हैं।

Common pitfalls

पहला pitfall है केवल main रखना और exports भूल जाना। दूसरा है files न सीमित करना, जिससे tests या drafts publish हो सकते हैं। तीसरा है README का stale हो जाना। चौथा है Unicode support को ज्यादा promise करना; यह truncate JavaScript string length use करता है, grapheme segmentation नहीं। पांचवां है Claude Code को package name, scope, 2FA, Trusted Publishing और final release approval तय करने देना।

Claude Code prompt template

Create a TypeScript npm package.

Goal:
- Package name: @acme/string-kit
- Support both ESM import and CJS require
- Use tsup to emit dist/index.js, dist/index.cjs, and dist/index.d.ts
- Include README generation, Vitest tests, and npm pack verification

Constraints:
- Only touch package.json, tsconfig.json, tsup.config.ts, src, scripts, and .github/workflows
- Do not use pseudocode; the project must run after npm install
- Do not publish source maps or unnecessary test files in the package tarball

Acceptance criteria:
- npm test passes
- npm run build passes
- npm pack --dry-run output is summarized
- ESM import and CJS require smoke tests are shown
- List the human release checks before npm publish

CTA: release workflow को template बनाएं

npm package पहली release के बाद खत्म नहीं होता। README, CI Node version, dependencies, permissions और SemVer strategy बदलते रहते हैं। पहले free Claude Code cheatsheet से safe prompts और verification commands रखें। Reusable templates के लिए ClaudeCodeLab products देखें। Team में CLAUDE.md, CI, review rules और publish permissions सेट करने हों तो Claude Code training और consultation देखें।

इस workflow को Windows temporary directory में चलाकर देखा: npm install, npm test, npm run build, npm pack --dry-run और ESM/CJS node -e smoke tests pass हुए। Masa के काम में Claude Code से npm pack output explain करवाने से stale README, missing types और unexpected tarball files release से पहले जल्दी मिलते हैं।

सारांश

Claude Code npm package बनाना तेज करता है, लेकिन publish contract साफ होना चाहिए। package.json, exports, types, tsup, tests, README, npm pack और CI को एक workflow में जोड़ें। Release से पहले बस तीन चीजें पूछें: dist देखा, tarball देखा, और वही entry point import किया जो user करेगा।

#Claude Code #npm #package蜈ャ髢・ #TypeScript #OSS
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.