Creating Shareable and Reusable TypeScript Configuration (tsconfig.json)

·

2 min read

Creating Shareable and Reusable TypeScript Configuration (tsconfig.json)

Introduction

Creating a reusable tsconfig.json can greatly simplify managing TypeScript configurations across multiple projects. This tutorial will guide you through creating a shared TypeScript configuration as an NPM package, which you can easily integrate into various projects.

Steps to Create a Shareable tsconfig.json

Step 1: Initialize Project

Create a directory named tsconfig and initialize it:

npm init -y
# or
pnpm init

Step 2: Update package.json

Edit your package.json:

{
  "name": "@your-org/tsconfig",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "files": ["*.json"],
  "homepage": "https://yourhomepage.com",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/your/repo.git"
  },
  "bugs": {
    "url": "https://github.com/your/repo/issues"
  },
  "author": {
    "name": "your name",
    "email": "your email",
    "url": "your url"
  },
  "publishConfig": {
    "access": "public"
  }
}

Customize the fields like name, homepage, repository, bugs, and author to suit your package.

Step 3: Create tsconfig Files

Create base.json:

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Default",
  "compilerOptions": {
    "declaration": true,
    // ... other options ...
  },
  "exclude": ["node_modules"]
}

Create esm.json for ECMAScript modules:

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "ESM Library",
  "extends": "./base.json",
  "compilerOptions": {
    "lib": ["ES2020", "DOM"],
    "module": "ES2022",
    "target": "ES6"
  }
}

Create cjs.json for CommonJS modules:

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "CommonJS Library",
  "extends": "./base.json",
  "compilerOptions": {
    "lib": ["ES2020", "DOM"],
    "module": "CommonJS",
    "target": "ES6"
  }
}

Step 4: Publish the NPM Package

Publish your package:

npm publish
# or
pnpm publish

Step 5: Using the Shared tsconfig

Install the package in your projects:

npm install --save-dev --save-exact @your-org/tsconfig
# or
pnpm add --save-dev --save-exact @your-org/tsconfig

Extend it in your project's tsconfig.json:

{
  "extends": "@your-org/tsconfig/esm.json",
  "compilerOptions": {
    "outDir": "dist"
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

Conclusion

Congratulations! You now have a shareable and reusable TypeScript configuration that can be easily integrated into any TypeScript project. This approach ensures consistency across multiple projects and simplifies configuration management.