How to publish a typescript package to npm?

How to publish a typescript package to npm?

(2 min read)

In this blog we are going to make a sum package.

  1. Initialize a npm project and a git and github repo
npm init
  • content of .gitignore file
node_modules
/lib
  1. Answer all the following questions shown in the image. image

After answering all the questions, a package.json file will be created.

  1. Create a README.md file.

  2. Install dev dependencies

npm install -D prettier tslint tslint-config-prettier typescript
  1. Create a tsconfig.json file.
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}
  1. Create src/index.ts file
export const sum = (...numbers: number[]) => {
  let temp = 0;

  for (const num of numbers) {
    temp += num;
  }

  return temp;
};
  1. Add build, format, and lint command in package.json
{
"scripts": {
    "build": "tsc",
    "format": "prettier --write \"src/*.ts\"",
    "lint": "tslint -p tsconfig.json"
 }
}
  1. Add files and types in package.json
{
"files": [
    "lib/**/*"
  ],
  "types": "./lib/index.d.ts",
}
  • files are the folders that will be included in the published package.
  • types contains the typescript declarations.
  1. Run build command which will generate a lib directory that is included in the package.

  2. Add prepare, preversion, version and postversion commands in scripts.

{
 "scripts": {
    "prepare": "npm run build",
    "prepublishOnly": "npm test && npm run lint",
    "preversion": "npm run lint",
    "version": "npm run format && git add -A src",
    "postversion": "git push && git push --tags"
  }
}
  1. Login to npm
npm login
  1. Now we can publish public package using
npm publish --access public
  1. Add support for testing using vitest
  • Install vitest
npm install -D vitest
  • Create vitest config vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    // ...
  },
});
  • Add test command in scripts.
{
"scripts": {
    "test": "vitest"
  }
}
  • Create tests directory inside src and make a sum.test.ts file.
import { expect, test } from 'vitest';
import { sum } from '../index';

test('testing sum', () => {
  expect(sum(1, 2)).toBe(3);
  expect(sum(2, 10)).toBe(12);
  expect(sum(2, 5)).not.toBe(8);
  expect(sum(1, 2, 3, 4, 5, 6, 7, 8, 100)).toBe(136);
});
  1. After writing the test, we can publish a new version by updating the version using npm version command. In this case, we are making patch version.
npm version patch
npm publish

Repository link: sum package by baijanath