Codementor Events

Build and publish an NPM Typescript package

Published Jul 07, 2021Last updated Jan 02, 2022
Build and publish an NPM Typescript package

Typescript installation and quick test.

Globally Installing TypeScript:
You can use npm to install TypeScript globally, this means you can use the tsc command anywhere in your terminal. You can also use use npx when you have to run tsc.

npm install -g typescript

Typescript in your project:
Having TypeScript set up on a per-project basis lets you have many projects with many different versions of TypeScript, this keeps each project working consistently. You can also use -D (dev dependency) as it's only needed when developing the package.

npm install typescript -D

You can then run the TypeScript compiler using one of the following commands:

npx tsc

Let's test this quickly. Create a folder and add 1.ts file in that. Add some ts code to 1.ts as below -

export function multiply(a:number, b:number) {
    return a * b;
}

Now execute below command if you have installed typescript in project. You can see a transpile js file as 1.js.

npx tsc 1.ts

For gloabl installation you can also run by below command -

tsc 1.ts

Note: You might get below error - File C:\Users..\tsc.ps1 cannot be loaded. The file C:\Users..\tsc.ps1 is not digitally signed. This is not a type script error it more to do with ps execution policy.You can fix by running below command -

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Next we will create npm package from the scarch. Let's create a new project folder and perform below steps -

Build and Publish

Create package.json in root directory. Use -y for default values.

npm init -y

Add typescript dev dependency to your project. devDependencies will only be installed when you run npm install, but not when the end-user installs the package.
For example, Typescript is only needed when developing the package, but it’s not needed while using the package.

npm i typescript -D

In order to compile Typescript we also need a tsconfig.json file. you can add by run below command.

tsc --init

You will see many fields in the file and some of important we have uncommented.
target: We want to compile to es5 since we want to build a package with browser compatibility.
module: Use commonjs for compatibility.
declaration: When you building packages, this should be true. Typescript will then also export type definitions together with the compiled javascript code so the package can be used with both Typescript and Javascript. And you can see the definition file in index.d.ts.
outDir: Compiled output will be written to this folder. In our case it is lib folder.
include: Source files path. In our case src folder
exclude: We don’t want to transpile node_modules, neither tests since these are only used during development. Use this if need to exclude such files.

Check which account you have logged in -

npm whoami

If this is not the correct account then login with correct npmjs account.

npm login

Now open you project in vs code. Your package.json file should look like this-

{
  "name": "@bookindesk/test123",
  "version": "1.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "npx tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.3.4"
  }
}

And tsconfig.json should look like this.

{
  "compilerOptions": {
    "incremental": true,            /* Enable incremental compilation */
    "target": "es5",                /* Specify ECMAScript target version: */
    "module": "commonjs",           /* 'none', 'commonjs', 'amd', 'system', etc */
    "declaration": true,            /* Concatenate & emit output to single file.*/
    "outDir": "lib",                /* Redirect output to the directory. */
    "esModuleInterop": true,        /* Enables intero between CommonJS and ES */
    "skipLibCheck": true,           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently */
  },
  "include": [
    "src"
  ]
}

As you can see we are using "src" as source file, add index.ts file in the src folder of your project. index.ts will look like this -

export function multiply(a:number, b:number) {
    return a * b;
}

Now build the project using package.json build script.

npx tsc

Since you have configured lib as your output path. you will the package files in lib folder.

Now you need to publish to npmjs

npm publish

Note in my case package was already existing and I just updated the version. If this new package you need to run below command -

npm publish --access public

By default, scoped packages are published with private visibility and it looks for Payment. In case you just need to test, skip the Payment/forbidden error
you need to publish a package with public visibility. If you have included Readme.md file then this will nicely render in your published location.

link

Consuming npm package

Now create a another another client project to consume the published package.

Add package json as above to this project.

npm init -y

Install the above published package locally by executing -

npm install @bookindesk/test123

Add index.ts file add below code -

import {multiply} from '@bookindesk/test123/lib';
let x = multiply(2,3);
console.log(x);

Now complie the index.ts to generate index.js by -

import {multiply} from '@bookindesk/test123/lib';
let x = multiply(2,3);
console.log(x);

And now run the index.js by

node index.js

You also combine above 2 commands as -

npx tsc index.ts | node index.js
Discover and read more posts from DhananjayKumar
get started
post commentsBe the first to share your opinion
CaliViking
2 years ago

Thank you for a very nice and concise writeup. I really like that you refer to the file names that you show the content of, too many articles make the assumption that the reader should know what they are looking at.

One small suggestion; in package.json, change from:
“main”: “index.js”
to
“main”: “./lib/index.js”

This will allow the import statement in index.ts to be changed from:
import {multiply} from ‘@bookindesk/test123/lib’;
to
import {multiply} from ‘@bookindesk/test123’;

Which is a lot easier to understand. The fact that the package placed the main entry point in the lib folder should be abstracted from the user of the package.

Show more replies