How to Create a TypeScript NPM Package

· 2 min read · 297 words
#typescript #npm #webdev

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.

$ 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 (key fields)
{
  "main": "dist/index.js",
  "types": "dist/index.d.ts"
}
// src/index.ts
export function myLibraryFunction() {}

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.

$ mkdir testproj && cd testproj
$ npm init
$ 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 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

Your package is now live on NPM. Anyone can install it with npm install <your-package-name>.