NPM Packages with TypeScript

5 min readSep 26, 2021

The more I play with the programming, the more I realize that I am often rewriting the same code. I therefore decided to upload some functions to NPM. But how can I create an NPM package using TypeScript? Well, I had to put together a few guides and do some tests. These are the steps I followed.

Initialize the package and install TypeScript

I create the package.json file with default values:

npm init -y

Then I add the node_modules folder among the paths to ignore in .gitignore.

I install TypeScript:

npm install --save-dev typescript

I configure the tsconfig.json file:

"compilerOptions": {
"outDir": "./lib",
"module": "ES2020", // or commonjs
"target": "ES2019",
"lib": [
"declaration": true,
"strict": true
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]

I create a src folder in which to put the starting code. Then I add the index.ts file:

const myCustomFunction = (name: string):string => `Hello ${name}`;
function ciao(name: string): string {
return `Ciao ${name}`;

export { myCustomFunction, ciao};

I add a script to package.json to start compiling the ts files:

"scripts": {
"build": "tsc"

I use the npm run build command to compile the files:

npm run build

After running the command I can see a new folder: lib. Inside there are 2 files: index.js with the compiled code and index.d.ts with the type definitions.

I’m not interested in comparing with source control the generated files. I add the lib folder to .gitignore:


For NPM packages I want the opposite. I want to make only the compiled files visible and not the source files. To do this I add to package.json:

// ...
"files": [

Add ESLint




I'm a hobby programmer, experimenting with Svelte, Javascript, Construct 3 and magic tools