Find and parse the tsconfig.json file from a directory path

Overview

get-tsconfig Latest version

Find and parse tsconfig.json files.

Features

  • Zero dependencies (not even TypeScript)
  • Tested against TypeScript for accuracy
  • Supports comments & dangling commas in tsconfig.json
  • Resolves extends
  • Validates and throws parsing errors
  • Tiny! 3 kB Minified + Gzipped

πŸš€ Install

npm install get-tsconfig

πŸ™‹β€β™€οΈ Why?

For TypeScript related tooling to correctly parse tsconfig.json file without depending on TypeScript.

πŸ‘¨β€πŸ« Usage

import getTsconfig from 'get-tsconfig'

// Finds tsconfig.json in the current directory
console.log(getTsconfig())

// Find tsconfig.json from a TypeScript file path
console.log(getTsconfig('./path/to/index.ts'))

// Find tsconfig.json from a directory file path
console.log(getTsconfig('./path/to/directory'))

// Explicitly pass in tsconfig.json path
console.log(getTsconfig('./path/to/tsconfig.json'))

βš™οΈ API

getTsconfig(searchPath?: string, configName?: string)

Searches for a tsconfig.json file and parses it. Returns null if a config file cannot be found, or an object containing the path and parsed TSConfig object if found.

Returns:

type TsconfigResult = {
    /**
     * The path to the tsconfig.json file
     */
    path: string | undefined

    /**
     * The resolved tsconfig.json file
     */
    config: TsConfigJsonResolved
} | null

searchPath

Type: string

Default: process.cwd()

Accepts a path to a file or directory to search up for a tsconfig.json file.

configName

Type: string

Default: tsconfig.json

The file name of the TypeScript config file.

FAQ

How can I use TypeScript to parse tsconfig.json?

This package is a re-implementation of TypeScript's tsconfig.json parser.

However, if you already have TypeScript as a dependency, you can simply use it's API:

import {
    sys as tsSys,
    findConfigFile,
    readConfigFile,
    parseJsonConfigFileContent
} from 'typescript'

// Find tsconfig.json file
const tsconfigPath = findConfigFile(process.cwd(), tsSys.fileExists, 'tsconfig.json')

// Read tsconfig.json file
const tsconfigFile = readConfigFile(tsconfigPath, tsSys.readFile)

// Resolve extends
const parsedTsconfig = parseJsonConfigFileContent(
    tsconfigFile.config,
    tsSys,
    path.dirname(tsconfigPath)
)
Comments
  • feat: support yarn pnp

    feat: support yarn pnp

    close #26 close https://github.com/import-js/eslint-import-resolver-typescript/issues/130

    continue #27

    I'll try to add a test case later, and it has been confirmed to be working as expected at https://github.com/import-js/eslint-import-resolver-typescript/pull/133 by `yarn patch`.
    opened by JounQin 17
  • Support jsconfig.json

    Support jsconfig.json

    It would be nice to support jsconfig.json.

    They're distinct files, in that they are configuration files for two different languages, so you can't necessarily use tsconfig.json in its place. Next.js for instance doesn't allow you to compile a project as a Javascript project using tsconfig.json.

    However they are made by the same team and serve some of the same purposes, so it would be great to have an option to use the same package to get it, rather than have an entirely new package just to add support for one variant.

    This issue comes from https://github.com/import-js/eslint-import-resolver-typescript/issues/73

    opened by rbong 7
  • Resolve error: File not found when using yarn PnP linker

    Resolve error: File not found when using yarn PnP linker

    We have this extends in our tsconfig.json

    "extends": "@equisoft/typescript-config/tsconfig.standards.json"
    

    I took a look at #21 and it seems the resolveExtends expects the extend to be in node_modules.

    Discovered this issue while trying to update to eslint-import-resolver-typescript@v3 which uses this library.

    needs reproduction 
    opened by meriouma 5
  • throws an error if the extends resolves to a JS file

    throws an error if the extends resolves to a JS file

    Hi!

    This code looks for require.resolve result - and only if that's not found does it try path.join(extendsPath, 'tsconfig.json').

    The problem is what if require.resolve resolves to an index.js file. Then we try using that instead of path.join(extendsPath, 'tsconfig.json').

    Then we try to read the JSON file. But it's JS not JSON, so we throw an error.

    Example:

    "extends": "@company/tsconfig"
    

    @company/tsconfig package.json:

    "main": "./src/index.js"
    

    @company/tsconfig tsconfig.json

    {
      // normal tsconfig.json
    }
    

    To resolve this we should do the resolving closer to how TypeScript does it. In this case, it would never resolve a .JS file, only .json. Perhaps if the filename is not .json we then attempt path.join(extendsPath, 'tsconfig.json').

    bug 
    opened by dylang 5
  • Unexpected `Error: Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?`

    Unexpected `Error: Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?`

    https://github.com/vitejs/vite/runs/7047103190?check_suite_focus=true#step:10:93

    reproduction: https://github.com/JounQin/vite/tree/chore/tsx_esno

    run pnpm i && pnpm build

    Maybe related to #16

    released 
    opened by JounQin 4
  • extends node_modules json with same name dir results error

    extends node_modules json with same name dir results error

    {
      "node_modules/@1stg/tsconfig/package.json": {
        "name": "@1stg/tsconfig"
      },
      "node_modules/@1stg/tsconfig/lib/.gitkeep": "",
      "node_modules/@1stg/tsconfig/lib.json": {
        "compilerOptions": {
          "jsx": "react-jsx"
        }
      },
      "tsconfig.json": {
        "extends": "@1stg/tsconfig/lib"
      }
    }
    
    Error: File '@1stg/tsconfig/lib' not found.
        at null.x (/workspace/get-tsconfig/dist/index.js:3:5193)
        at null.I (/workspace/get-tsconfig/dist/index.js:3:5895)
        at null.ie (/workspace/get-tsconfig/dist/index.js:3:6878)
        at null.<anonymous> (/workspace/get-tsconfig/tests/specs/extends.spec.ts:382:22)
        at null.<anonymous> (/workspace/get-tsconfig/node_modules/.pnpm/[email protected]/node_modules/manten/dist/index.js:1:676)
    

    See #21 for reproduction details.

    opened by JounQin 1
  • fix(types): compilerOptions.paths to require values

    fix(types): compilerOptions.paths to require values

    Update type-fest to latest to fix typing issue regarding paths.

    https://github.com/sindresorhus/type-fest/pull/404

    As an example of what it fixes (look for the // @ts-ignore):

    const getTsConfigBasePaths = (tsConfigFile) => {
      const parsedTsConfig = getTsconfig(tsConfigFile);
      if (parsedTsConfig === null) {
        throw new Error(`Cannot find tsconfig file: ${tsConfigFile}`);
      }
      const tsPaths = parsedTsConfig.config.compilerOptions?.paths ?? {};
    
      return Object.entries(tsPaths).length > 0
        ? // @ts-ignore
          pathsToModuleNameMapper(tsPaths, {
            prefix: '<rootDir>/',
          })
        : {};
    };
    

    PS: added a manual patch to see if it works: https://github.com/belgattitude/perso/pull/365/files

    released 
    opened by belgattitude 1
  • chore(deps): added type-fest to deps

    chore(deps): added type-fest to deps

    First of all congrats. This is very useful.

    I'd like to add a dependency on type-fest imported from https://github.com/privatenumber/get-tsconfig/blob/a107c720daa5045426eef70df2601daac6defd0f/src/types.ts#L1.

    I know that this lib is zero-deps :smile: ... and there's other options I can propose if it's a blocker.

    What would it fix ?

    • Experience with different packages managers will work better (pnpm, yarn pnp). Future is going strict
    • I have typescript issues regarding paths fixed in the latest TsConfigJson. See https://github.com/sindresorhus/type-fest/releases/tag/v2.13.1. Without stating the dep, resolution algorithm fallbacks to what is present... No real control of versions there.
    Example of yarn why type-fest
    yarn why type-fest
    β”œβ”€ @belgattitude/base-ui@workspace:packages/base-ui
    β”‚  └─ type-fest@npm:2.13.1 (via npm:^2.13.0)
    β”‚
    β”œβ”€ @contentlayer/core@npm:0.2.5
    β”‚  └─ type-fest@npm:2.13.1 (via npm:^2.12.2)
    β”‚
    β”œβ”€ @contentlayer/core@npm:0.2.5 [0efb3]
    β”‚  └─ type-fest@npm:2.13.1 (via npm:^2.12.2)
    β”‚
    β”œβ”€ @contentlayer/utils@npm:0.2.5
    β”‚  └─ type-fest@npm:2.13.1 (via npm:^2.12.2)
    β”‚
    β”œβ”€ @contentlayer/utils@npm:0.2.5 [0efb3]
    β”‚  └─ type-fest@npm:2.13.1 (via npm:^2.12.2)
    β”‚
    β”œβ”€ ansi-escapes@npm:4.3.2
    β”‚  └─ type-fest@npm:0.21.3 (via npm:^0.21.3)
    β”‚
    β”œβ”€ globals@npm:13.15.0
    β”‚  └─ type-fest@npm:0.20.2 (via npm:^0.20.2)
    β”‚
    β”œβ”€ meow@npm:6.1.1
    β”‚  └─ type-fest@npm:0.13.1 (via npm:^0.13.1)
    β”‚
    β”œβ”€ meow@npm:8.1.2
    β”‚  └─ type-fest@npm:0.18.1 (via npm:^0.18.0)
    β”‚
    β”œβ”€ read-pkg-up@npm:7.0.1
    β”‚  └─ type-fest@npm:0.8.1 (via npm:^0.8.1)
    β”‚
    β”œβ”€ read-pkg@npm:5.2.0
    β”‚  └─ type-fest@npm:0.6.0 (via npm:^0.6.0)
    β”‚
    └─ website@workspace:apps/website
       └─ type-fest@npm:2.13.1 (via npm:2.13.1)
    

    Alternatives

    • [ ] To avoid adding a dep, keep a local version of TsConfigJson
    • [ ] Add to peerDependencies (not optional in this sepcific case). It changes the way to install too.
    • [ ] Others ?

    Let me know.

    opened by belgattitude 1
  • fix(extends): baseUrl that points to parent path

    fix(extends): baseUrl that points to parent path

    Problem

    When a and b in path.relative(a, b) resolve to the same path, path.relative() returns an empty string instead of . or ./. This caused baseUrl to appear undefined.

    closes https://github.com/esbuild-kit/esm-loader/issues/26

    Changes

    When path.relative() return an empty string, fall back to ./.

    released 
    opened by privatenumber 1
  • extends module-name/config does not try module-name/config.json

    extends module-name/config does not try module-name/config.json

    To copy how tsc resolves config names, we should append .json. We're doing that today with relative paths, but not when it comes from a module.

    PR provided: #10

    Thanks!

    opened by dylang 1
  • Doesn't support extends: absolute path

    Doesn't support extends: absolute path

    This kind of tsconfig.json is not supported:

    {"extends": "/Users/ak/proj/foo/node_modules/bar/tsconfig.json"}
    

    I could create a PR fixing this but looks like fs-fixture doesn't support absolute paths either (unless I'm missing something)

    opened by andykog 2
  • Align properties of `TsConfigJsonResolved` with TypeScript's `ParsedCommandLine`

    Align properties of `TsConfigJsonResolved` with TypeScript's `ParsedCommandLine`

    See also ParsedCommandLine

    https://github.com/microsoft/TypeScript/blob/fd3a84c3f0c80cb201c47399a055625f919a9b91/lib/typescriptServices.d.ts#L3168-L3178


    I'd like to replace parsing tsconfig.json from TypeScript to get-config more seamlessly.

    It would be a BREAKING CHANGE.

    opened by JounQin 3
Releases(v4.2.0)
Owner
hiroki osame
I'm on a mission to open source my solutions πŸš€
hiroki osame
Sort tsconfig.json compilerOptions

sort-compiler-options Sort tsconfig.json compilerOptions in the same order as the TSConfig Reference (Support v4.5.5 or less) Install npm i sort-compi

P-Chan 6 Oct 19, 2022
Validate directory structure and file contents with an extension of JSON schema.

directory-schema-validator Description Validate directory structure and file contents with an extension of JSON schema. Install Install using NPM or s

Justin Poehnelt 5 Nov 1, 2022
Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de crΓ©er un tunnel https pour c

AILI Fida Aliotti Christino 2 Mar 29, 2022
Userland module that implements the module path mapping that Node.js does with "exports" in package.json

exports-map Userland module that implements the module path mapping that Node.js does with "exports" in package.json npm install exports-map Usage co

Mathias Buus 9 May 31, 2022
Easily create test fixtures at a temporary file-system path

fs-fixture Easily create test fixtures at a temporary file-system path. Support this project by ⭐️ starring and sharing it. Follow me to see what othe

hiroki osame 13 Dec 15, 2022
Find stale dependencies in the package.json file(s).

staledeps Find stale dependencies in the package.json file(s). Installation npm install -g staledeps Or simply using npx, the package runner bundled

Michael Mok 6 Dec 15, 2022
Simple JSON parse/stringify for the Wren programming language

wren-json Simple JSON parse/stringify for the Wren programming language. Parses strict json and relaxed json Comments Unquoted keys Trailing commas St

.ruby 8 May 18, 2022
Group and sort Eleventy’s verbose output by directory (and show file size with benchmarks)

eleventy-plugin-directory-output Group and sort Eleventy’s verbose output by directory (and show file size with benchmarks). Sample output from eleven

Eleventy 16 Oct 27, 2022
JCS (JSON Canonicalization Scheme), JSON digests, and JSON Merkle hashes

JSON Hash This package contains the following JSON utilties for Deno: digest.ts provides cryptographic hash digests of JSON trees. It guarantee that d

Hong Minhee (ζ΄ͺ 民憙) 13 Sep 2, 2022
JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

Aykut Saraç 20.6k Jan 4, 2023
Prisma 2+ generator to emit a JSON file that can be run with json-server

Prisma JSON Server Generator A Prisma generator that automates creating a JSON file that can be run as a server from your Prisma schema. Explore the o

Omar Dulaimi 14 Jan 7, 2023
A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM deffiniation and appropriate file structure.

Welcome to function-stencil ?? A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM

Ben Smith 21 Jun 20, 2022
Serve file server with single zip file as file system in Deno.

zipland Serve file server with one-single zip file in Deno. Support zip just zip32 with deflated or uncompressed serving plaintext deflate Examples Yo

Yongwook Choi 18 Nov 2, 2022
Feel free to create new file, don't hesitate to pull your code, the most important thing is that the file name here must match your nickname so that file does not conflict with other people.

Hacktoberfest Indonesia Apa Itu Hacktoberfest ? Hacktoberfest adalah acara tahunan yang bertujuan untuk mendorong berkontribusi kedalam ekosistem open

Juan Daniel 5 Dec 15, 2022
SWC plugin for transforming import path.

swc-plugin-transform-import Inspired from babel-plugin-transform-imports Installation npm i -D swc-plugin-transform-import Uses with webpack-config //

Ankit Chouhan 35 Dec 24, 2022
This package enables you to mount your Remix app at a different path than root

Remix Mount Routes This package enables you to mount your Remix app at a different path than root. ?? Installation > npm install -D remix-mount-routes

Kiliman 26 Dec 17, 2022
Detect the executable python interpreter cmd in $PATH.

detect-python-interpreter Detect the executable python interpreter cmd in $PATH. Installation $ npm install --save detect-python-interpreter Usage con

Khaidi Chu 2 Apr 12, 2022
Path-finding & Sorting algorithms Visualizer

Update - Changelog ?? 09.05.2022 AlgoVision is now fully mobile-responsive for all its features ! On mobile, the 'Mouse Chase' option in Dynamic Mode

Eliya Shalom 23 Dec 18, 2022
Sort imports by path - VS Code extension

Import sort by absolute path The sorting algorithm will group each item in the array and sort (alphabetically) its children that starts with the path

Richard Bidin 3 Feb 2, 2022