Table of contents
Library setup
In this article, you'll learn how to create a typescript shared library that can be used in multiple projects simultaneously, which can be pretty helpful, especially when it comes to mono repositories.
First create a lib project:
mkdir lib-app && cd lib-app
Init npm:
npm init --yes
Update package.json to have the following properties and values:
{
"name": "lib-app",
"version": "1.0.0",
"description": "A simple math library.",
"main": "lib/index.js",
"types": "lib",
"scripts": {
"build": "tsc p ."
},
"keywords": [],
"author": "",
"license": "ISC"
}
Install typescript as a dev dependency:
npm install typescript --save-dev
Init a typescript project:
npx tsc --init
Update tsconfig.json to the following:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"outDir": "lib",
"rootDir": "src",
"composite": true,
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
}
}
Create source code directories:
mkdir src && mkdir src/calc
Add source code.
touch src/calc/index.ts src/index.ts
src/calc/index.ts:
export const add = (x: number, y: number) => {
return x + y;
}
src/index.ts:
export * from './calc';
From this point, we're ready to reuse our library.
Library installation
Create a demo project:
mkdir demo-app && cd demo-app
Init npm:
npm init --yes
Install typescript as a dev dependency:
npm install typescript --save-dev
Update package.json to the following:
{
"name": "demo-app",
"version": "1.0.0",
"description": "A demo project.",
"main": "index.js",
"scripts": {
"build": "tsc --build .",
"start": "npm run build && node ./dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Init typescript project:
npx tsc --init
Update tsconfig.json to the following:
{
"compilerOptions": {
"baseUrl": "./",
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "dist",
"forceConsistentCasingInFileNames": true
},
"references": [
{ "path": "../lib-app/" }
]
}
Notice that we've added the
Add file
import { add } from '../../lib-app';
console.log(add(1,3));
Now we can run the project:
npm run start
You also can publish the typescript library to npm. More information is here.