How to publish a typescript package to npm?
(2 min read)In this blog we are going to make a sum
package.
- Initialize a npm project and a git and github repo
npm init
- content of .gitignore file
node_modules
/lib
- Answer all the following questions shown in the image.
After answering all the questions, a package.json file will be created.
-
Create a README.md file.
-
Install dev dependencies
npm install -D prettier tslint tslint-config-prettier typescript
- Create a tsconfig.json file.
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./lib",
"strict": true
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}
- Create src/index.ts file
export const sum = (...numbers: number[]) => {
let temp = 0;
for (const num of numbers) {
temp += num;
}
return temp;
};
- Add build, format, and lint command in package.json
{
"scripts": {
"build": "tsc",
"format": "prettier --write \"src/*.ts\"",
"lint": "tslint -p tsconfig.json"
}
}
- 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.
-
Run
build
command which will generate alib
directory that is included in the package. -
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"
}
}
- Login to npm
npm login
- Now we can publish public package using
npm publish --access public
- 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);
});
- 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