Hi

How to create a TypeScript NPM package

Jul 2022
How to create and publish a TypeScript library to NPM simply and easily

Want to add more chaos to the JavaScript ecosystem? It's easier than you thought!

1. Initial setup

Initialise NPM application. Follow the prompts to include the relevant information.

Note: I am using TypeScript, Jest and Prettier because I like them. They are not required.

Why I prefer TypeScript

$ npm init
$ npm i -D typescript jest @types/jest ts-jest prettier

Create your git repository. We need a remote git repository for NPM to download it from.

$ git init
$ git add .
$ git commit -m "Initial commit"
$ git remote add origin <YOUR_REPO_HERE>

Add a .gitignore file with anything you want to keep private.

2. Add your code and config

// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "esModuleInterop": true,
    "skipLibCheck": true,
  },
  "exclude": ["node_modules", "dist", "tests"]
  ...
}
// package.json
{
  ...
  "main": "dist/index.js",
  "types": "dist/index.d.ts"
  ...
}
// src/index.ts
export function myLibraryFunction() {}

I'll leave out the tests for this one ;)

3. Build your package

$ tsc

You should now see a dist directory. This contains your compiled app, including type definitions.

4. Test it works locally

Link your local project for testing.

$ sudo npm link

Now, create a new NPM project elsewhere in your system.

my_project $ cd ..
Projects $ mkdir testproj && cd testproj
testproj $ npm init

From this new project, we can install our original package.

$ npm link <project_name_from_package_json>

You should now be able to use your package as a normal NPM package. Test everything works, then publish!

5. Publish to NPM

You will need an account with NPM. Either create one at npmjs.com/signup, or run the command npm adduser and follow the instructions.

If you already have an account, run npm login to login to the CLI.

Now it's time to publish!

$ npm publish
Back to top

© 2025 alister.codes