How to package an existing typescript project and release it on npm in 5 steps

How to package an existing typescript project and release it on npm in 5 steps

We will ensure the following things

  • The npm package only contains the relevant javascript files along with type declarations
  • Our public repo doesn't need to contain any javascript file

My current typescript project

It has the following file structure Screen Shot 2021-07-05 at 1.42.16 AM

Below is the content of getJoke.ts

import fetch from 'node-fetch';

export default async (): Promise<string> => {
  const res = await fetch('https://official-joke-api.appspot.com/random_joke');
  const json = await res.json();
  const joke = json.setup + '\n' +json.punchline;
  return joke;
}

Below is the content of index.ts

import getJoke from './getJoke'

for (let i = 0; i < 20; i++) {
  getJoke().then(joke => {
    console.log(joke)
    console.log('\n \n')
  })
}

It's a simple project which prints 20 random jokes.

I used

tsc -init

and

npm init

to generate my tsconfig.json and package.json files respectively.

My package.json is almost unchanged, the only difference is the addition of a script

  "scripts": {
    "main": "tsc && node ./dist/index.js"
  }

My tsconfig.json has a few changes. I deleted all the irrelevant configurations and add paths to outDir and rootDir. Below is my tsconfig.json

{
  "compilerOptions": {                     
    "target": "es5",
    "module": "commonjs",
    "lib": ["es2017", "es7", "es6", "dom"],                         
    "outDir": "./dist",                             
    "rootDir": "./src",                             
    "esModuleInterop": true,                       
    "forceConsistentCasingInFileNames": true ,
    "declaration": true     
  }
}

Steps to Publish the typescript project

Step1: Update tsconfig.json

Add the following to your tsconfig.json

"declaration": true

Step2: Update package.json

First we will need to add the path to our types.

  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",

We will need to add a new key-value for "types" the value should be the same as that of "main". The only difference is the extension, the value for "types" should have ".d.ts" instead of ".js"

We will need to add another key-value pair

  "files":[
    "dist/**"
  ]

This will tell npm which files to include in the package. Since we only want to include our compiled javascript files, we only include the files inside the dist folder. If your JS files are stored in some other directory, ensure you whitelist the correct files/path.

###Step 3: Update .gitignore Add the following to gitignore

dist

This will ensure that our javascript files do not get pushed to our repo

###Step4: Confirm everything is working Run the following command

tsc && npm pack

This should create a zip file. The zip file is essentially a representation of what your package would look like when installed using npm. After you run the command, it will also generate an output with the file contents. Ensure the javascript files are included in the package.

###Step5: Publish Update the name,author,license etc in package.json if you'd like. Once you are ready, simply run the below command

tsc && npm publish

If you get an error like below

npm ERR! publish Failed PUT 404

Try running the following command to login the npm using the cli

npm login

and then adding an user to the registry

npm adduser

Ensure you have an npm account with a verified addres.

If you want to republish, run the following command

tsc && npm version <new version number> && npm publish

Let's try importing our package

We will import it in a typescript file and then in a javascript file.

Install your packages

npm i typescript-jokes-rahul

You can check the package inside node_modules to confirm that right files have been added to the package.

Importing package in JavaScript

const joke = require('typescript-jokes-rahul/dist/getJoke')

joke.default()
    .then(
        joke => console.log(joke),
)

Importing package in typescript

import getJoke  from 'typescript-jokes-rahul/dist/getJoke'

getJoke()
    .then(
        joke => console.log(joke),
)

In my next article, I will talk about how to fix the weird import paths.

Resources

GitHub Repo: https://github.com/rahulbanerjee26/typescript-example-package

Npm Package:
https://www.npmjs.com/package/typescript-jokes-rahul

https://medium.com/cameron-nokes/the-30-second-guide-to-publishing-a-typescript-package-to-npm-89d93ff7bccd