How to package an existing typescript project and release it to npm in 5 steps
Tags: typescript, npm, tutorial, codenewbie
Published: 2021-07-05 07:41:51

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5d1rdx9tekg3ixjlhfgh.png)

Below is the content of getJoke.ts
```typescript
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
```typescript
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 
```bash 
tsc -init
``` 
and 
```bash
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
```json
  "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

```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
```JSON
"declaration": true 
```
#### Step2: Update package.json
First we will need to add the path to our types.
 
```json
  "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
```JSON
  "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
```bash
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
```bash
tsc && npm publish
```

If you get an error like below
```bash
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
```bash
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
```bash
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
```javascript
const joke = require('typescript-jokes-rahul/dist/getJoke')

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

Importing package in typescript
```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. 

<!-- wp:heading -->
<h2>Resources</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>GitHub Repo:&nbsp;<a href="https://github.com/rahulbanerjee26/typescript-example-package">https://github.com/rahulbanerjee26/typescript-example-package</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Npm Package:<br><a href="https://www.npmjs.com/package/typescript-jokes-rahul">https://www.npmjs.com/package/typescript-jokes-rahul</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://medium.com/cameron-nokes/the-30-second-guide-to-publishing-a-typescript-package-to-npm-89d93ff7bccd">https://medium.com/cameron-nokes/the-30-second-guide-to-publishing-a-typescript-package-to-npm-89d93ff7bccd</a></p>
<!-- /wp:paragraph -->