GithubHelp home page GithubHelp logo

privatenumber / get-tsconfig Goto Github PK

View Code? Open in Web Editor NEW
162.0 5.0 11.0 1.26 MB

TypeScript `tsconfig.json` parser & paths resolver

License: MIT License

TypeScript 100.00%
node typescript tsconfig get find parse paths

get-tsconfig's Introduction

get-tsconfig Latest version npm downloads

Find and parse tsconfig.json files.

Features

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

Already a sponsor? Join the discussion in the Development repo!

Install

npm install get-tsconfig

Why?

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

API

getTsconfig(searchPath?, configName?, cache?)

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

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

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.

cache

Type: Map<string, any>

Default: new Map()

Optional cache for fs operations.

Example

import { getTsconfig } from 'get-tsconfig'

// Searches for tsconfig.json starting 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'))

// Search for jsconfig.json - https://code.visualstudio.com/docs/languages/jsconfig
console.log(getTsconfig('.', 'jsconfig.json'))

parseTsconfig(tsconfigPath, cache?)

The tsconfig.json parser used internally by getTsconfig. Returns the parsed tsconfig as TsConfigJsonResolved.

tsconfigPath

Type: string

Required path to the tsconfig file.

cache

Type: Map<string, any>

Default: new Map()

Optional cache for fs operations.

Example

import { parseTsconfig } from 'get-tsconfig'

// Must pass in a path to an existing tsconfig.json file
console.log(parseTsconfig('./path/to/tsconfig.custom.json'))

createFileMatcher(tsconfig: TsconfigResult, caseSensitivePaths?: boolean)

Given a tsconfig.json file, it returns a file-matcher function that determines whether it should apply to a file path.

type FileMatcher = (filePath: string) => TsconfigResult['config'] | undefined

tsconfig

Type: TsconfigResult

Pass in the return value from getTsconfig, or a TsconfigResult object.

caseSensitivePaths

Type: boolean

By default, it uses is-fs-case-sensitive to detect whether the file-system is case-sensitive.

Pass in true to make it case-sensitive.

Example

For example, if it's called with a tsconfig.json file that has include/exclude/files defined, the file-matcher will return the config for files that match include/files, and return undefined for files that don't match or match exclude.

const tsconfig = getTsconfig()
const fileMatcher = tsconfig && createFileMatcher(tsconfig)

/*
 * Returns tsconfig.json if it matches the file,
 * undefined if not
 */
const configForFile = fileMatcher?.('/path/to/file.ts')
const distCode = compileTypescript({
    code: sourceCode,
    tsconfig: configForFile
})

createPathsMatcher(tsconfig: TsconfigResult)

Given a tsconfig with compilerOptions.paths defined, it returns a matcher function.

The matcher function accepts an import specifier (the path to resolve), checks it against compilerOptions.paths, and returns an array of possible paths to check:

function pathsMatcher(specifier: string): string[]

This function only returns possible paths and doesn't actually do any resolution. This helps increase compatibility wtih file/build systems which usually have their own resolvers.

Example

import { getTsconfig, createPathsMatcher } from 'get-tsconfig'

const tsconfig = getTsconfig()
const pathsMatcher = createPathsMatcher(tsconfig)

const exampleResolver = (request: string) => {
    if (pathsMatcher) {
        const tryPaths = pathsMatcher(request)

        // Check if paths in `tryPaths` exist
    }
}

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)
)

Sponsors

get-tsconfig's People

Contributors

13onthecode avatar andykog avatar belgattitude avatar jounqin avatar privatenumber avatar shun-shobon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

get-tsconfig's Issues

Does not load "extends" files correctly from symlinked directories

Problem

get-tsconfig resolves symlinks to real paths and uses resolved real paths as a base to resolve "extends" (this was implemented in #24).

This is incompatible with how TypeScript handles symlinks (it does not resolve symlinks).

As a result, when symlinked configs try to "extend" something from the origin directory, TypeScript loads extended files from the origin directory, while get-tsconfig produces a "File not found" error.

This is currently implemented in _parseTsconfig function:
https://github.com/privatenumber/get-tsconfig/blob/v4.7.3/src/parse-tsconfig/index.ts#L85-L90

Expected behavior

I'd expect get-tsconfig to not produce errors, and instead to not resolve symlinks to real paths, just as TypeScript does.

Minimal reproduction URL

https://stackblitz.com/edit/stackblitz-starters-gynqrn

TypeScript handles this config layout perfectly:

~/projects/stackblitz-starters-gynqrn/project
❯ tsc --showConfig
{
    "compilerOptions": {
        "outDir": "./dist",
        "rootDir": "./src",
        "noEmitOnError": false
    },
    "files": [
        "./src/index.ts"
    ],
    "include": [
        "config-template/../src"
    ]
}

~/projects/stackblitz-starters-gynqrn/project
❯ tsc --listEmittedFiles
TSFILE: /home/projects/stackblitz-starters-gynqrn/project/dist/index.js

get-tsconfig produces an error on encountering symlinked config which tries to extend from config located in the origin (non-symlinked) directory:

~/projects/stackblitz-starters-gynqrn
❯ node ./get-tsconfig-demo.js
Error: File '../tsconfig-custom-overrides.json' not found.
    at je (/home/projects/stackblitz-starters-gynqrn/node_modules/get-tsconfig/dist/index.cjs:3:9102)
    at te (/home/projects/stackblitz-starters-gynqrn/node_modules/get-tsconfig/dist/index.cjs:3:10068)
    at je (/home/projects/stackblitz-starters-gynqrn/node_modules/get-tsconfig/dist/index.cjs:3:9260)
    at te (/home/projects/stackblitz-starters-gynqrn/node_modules/get-tsconfig/dist/index.cjs:3:10068)
    at ie (/home/projects/stackblitz-starters-gynqrn/node_modules/get-tsconfig/dist/index.cjs:3:10783)
    at $e (/home/projects/stackblitz-starters-gynqrn/node_modules/get-tsconfig/dist/index.cjs:3:10888)
    at function (https://stackblitzstartersgynqrn-tzfv.w-corp-staticblitz.com/blitz.0314a412.js:352:196823)
    at Module.prototype._compile (node:internal/modules/cjs/loader:54:14871)
    at Module."] (node:internal/modules/cjs/loader:54:15550)
    at Module.prototype.load (node:internal/modules/cjs/loader:54:13457)
    at Module._load (node:internal/modules/cjs/loader:54:10535)
    at executeUserEntryPoint (node:internal/modules/run_main:125:731)
    at _0xd40aa0 (https://stackblitzstartersgynqrn-tzfv.w-corp-staticblitz.com/blitz.0314a412.js:350:56974)
    at _0x5c07a4 (https://stackblitzstartersgynqrn-tzfv.w-corp-staticblitz.com/blitz.0314a412.js:352:101852)
    at executeBootstrapper (https://stackblitzstartersgynqrn-tzfv.w-corp-staticblitz.com/blitz.0314a412.js:352:622137)
    at startExecution (https://stackblitzstartersgynqrn-tzfv.w-corp-staticblitz.com/blitz.0314a412.js:371:2925)
    at run (https://stackblitzstartersgynqrn-tzfv.w-corp-staticblitz.com/blitz.0314a412.js:371:1311)

Version

v4.7.3

Node.js version

v18.18.0

Package manager

npm

Operating system

Linux

Contributions

  • I plan to open a pull request for this issue
    I would open a pull request, but I don't know why the original decision to resolve symlinks was made, so I don't know what will break if I were to disable resolving symlinks.

  • I plan to make a financial contribution to this project

`paths` are unexpectedly resolved from context

Problem

This package says that it resolves extends, and is intended to work how the TypeScript compiler / language services do in figuring out your current configuration. But it doesn't do that.

Specifically, when TypeScript language services are resolving paths, any value for paths within tsconfig.json is resolved relative to the local tsconfig.json file (similar to Node resolution for modules). However, when this library is merging tsconfig configurations, it neither resolves paths nor keeps track of where those paths were declared.

This results in the "final" tsconfig having a paths definition that is altogether different from how TypeScript would resolve it, which makes the output difficult to use with a package like alias-reuse.

The use case is that with a Nuxt setup, a sub-directory is generated with a generated tsconfig.json file. I can manually resolve those paths knowing that the path information from get-tsconfig is wrong, but I thought it would still be good to file a bug.

Expected behavior

Either paths should fully resolve into full paths, or there should be some way to resolve those paths by knowing which file they came from OR there should be an option to do either. (Ideally, it would just resolve into the actual path.)

Minimal reproduction URL

https://stackblitz.com/edit/stackblitz-starters-em1thz?description=Starter%20project%20for%20Node.js,%20a%20JavaScript%20runtime%20built%20on%20Chrome%27s%20V8%20JavaScript%20engine&file=tsconfig.json,package.json,index.mjs,deep%2Fdeeper%2Ftsconfig.json,deep%2Ftsconfig.json&title=node.new%20Starter

Version

4.7.3

Node.js version

v18.18.0

Package manager

npm

Operating system

macOS

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

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.

e.replaceAll is not a function

Problem

UnhandledPromiseRejectionWarning: TypeError: e.replaceAll is not a function
    at oe (/xxx/node_modules/esbuild-loader/node_modules/get-tsconfig/dist/index.cjs:3:12968)
    at /xxx/node_modules/esbuild-loader/node_modules/get-tsconfig/dist/index.cjs:3:13576
    at Array.map (<anonymous>)
    at Object.Ve [as createFilesMatcher] (/xxx/node_modules/esbuild-loader/node_modules/get-tsconfig/dist/index.cjs:3:13551)
    at Object.ESBuildLoader (/xxx/node_modules/esbuild-loader/dist/index.cjs:52:35)
    at LOADER_EXECUTION (/xxx/node_modules/loader-runner/lib/LoaderRunner.js:132:14)
    at runSyncOrAsync (/xxx/node_modules/loader-runner/lib/LoaderRunner.js:133:4)
    at iterateNormalLoaders (/xxx/node_modules/loader-runner/lib/LoaderRunner.js:251:2)
    at /xxx/node_modules/loader-runner/lib/LoaderRunner.js:224:4
    at /xxx/node_modules/webpack/lib/NormalModule.js:920:15
(node:51114) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 21)

node: 12.7.0
esbuild-loader: 3.2.0,its dependencies: get-tsconfig "^4.6.2"

Expected behavior

fix it

Minimal reproduction URL

https

Version

v4.7.3

Node.js version

v12.7.0

Package manager

npm

Operating system

macOS

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

Tsconfig Extends + Base Url + Paths Causing Lint Error on 4.7.1

Problem

Link to reproduction url with steps in readme: https://github.com/matthewwolfe/tsconfig-extends-bug

I have an application that utilizes multiple tsconfigs that extend base tsconfigs that are published as packages separately and available via node_modules. On version 4.7.0 this works perfectly, 4.7.1 introduces an issue where the paths in the base config are not resolved properly. In the repository provided, the main branch produces a lint error, the pinned-version branch does not produce a lint error.

Expected behavior

Tsconfigs with base url and paths that are extended should work consistently with tsc

Minimal reproduction URL

https://github.com/matthewwolfe/tsconfig-extends-bug

Version

4.7.1

Node.js version

18.16.0

Package manager

npm

Operating system

macOS

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

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.

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)

Does not handle tsconfig without `baseUrl`

Problem

A "continuation" of #50 πŸ˜…

Nuxt 3.7.x changed the format of generated tsconfig again, which now less uses absolute paths but most importantly for some reason does not include baseUrl field. This causes get-tsconfig to resolve baseUrl to undefined and again eslint-import-resolver-typescript not to work properly.

Expected behavior

Resolved baseUrl must not be set to undefined, I guess.

Minimal reproduction URL

https://github.com/andreww2012/eslint-plugin-import-with-nuxt-3.6-false-reports

Version

v4.7.0

Node.js version

v16.20.2

Package manager

pnpm

Operating system

Windows

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

Error: Circularity detected while resolving configuration

Problem

If the extends configuration in tsconfig.json is an array, and each item in it further extends another configuration, it will cause getTsconfig to run and fail, with the following error message:

Error: Circularity detected while resolving configuration: /home/projects/vitest-dev-vitest-wulihl/tsconfigs/base.json
    at _0x15be0c._evaluate (https://vitestdevvitestwulihl-g131.w-corp-staticblitz.com/blitz.c9a8a620.js:352:379484)
    at async ModuleJob.run (https://vitestdevvitestwulihl-g131.w-corp-staticblitz.com/blitz.c9a8a620.js:181:2372)

Expected behavior

Minimal reproduction URL

https://stackblitz.com/edit/vitest-dev-vitest-wulihl?file=repro.mjs

Version

v4.7.2

Node.js version

v18.18.0

Package manager

npm

Operating system

Windows

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

replaceAll syntax issue with webpack's bundler in files-matcher.ts

Problem

In Vue2.X project, esbuild-loader which relies on get-tsconfig is used for packaging, There throw an exception in the cjs file "UnhandledPromiseRejectionWarning: TypeError: E.placeall is not a function ", this seems to be an unnecessary syntax upgrade in 4.7.3, please check it out.

Expected behavior

Use the replace syntax instead of replaceAll

Minimal reproduction URL

https://stackblitz.com/edit/can't-be-supported-in-vue2-with-webpack

Version

v4.7.3

Node.js version

v14.18.0

Package manager

npm

Operating system

Windows

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

Add support for TS v5's multiple config extensions

First of all, thanks a lot for your very helpful lib!

While tinkering with the TS v5 beta and preparing my monorepo for its coming changes, with multiple config extensions among others, I noticed most (if not all) of eslint-plugin-import's rules were broken in my TS files, with the following error:

Resolve error: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Array
    at new NodeError (node:internal/errors:399:5)
    at validateString (node:internal/validators:163:11)
    at Object.isAbsolute (node:path:1157:5)
    at be (/Users/acidoxee/Documents/projects/platform/node_modules/get-tsconfig/dist/index.cjs:3:7906)
    at J (/Users/acidoxee/Documents/projects/platform/node_modules/get-tsconfig/dist/index.cjs:3:9059)
    at J (/Users/acidoxee/Documents/projects/platform/node_modules/get-tsconfig/dist/index.cjs:3:9077)
    at Object.Te [as getTsconfig] (/Users/acidoxee/Documents/projects/platform/node_modules/get-tsconfig/dist/index.cjs:3:10154)
    at /Users/acidoxee/Documents/projects/platform/node_modules/eslint-import-resolver-typescript/lib/index.cjs:309:36
    at Array.map (<anonymous>)
    at initMappers (/Users/acidoxee/Documents/projects/platform/node_modules/eslint-import-resolver-typescript/lib/index.cjs:305:26)

As can be seen from the stacktrace, it originates from eslint-import-resolver-typescript, which is what eslint-plugin-import recommends to support TS files. This package uses your lib to resolve one or several tsconfig files.

From just a quick glance, I'm guessing this function here (among other places) is where multiple config extensions' support is missing, since this function is expecting a single requestedPath as string instead of the new string | string[] format available in TS v5:

export function resolveExtends(
requestedPath: string,
directoryPath: string,
) {

Would you be willing to add support for that feature to fully support TS v5? πŸ™

Improve compatible with pnpm

Like yarn PnP, pnpm would install all deps into node_modules/.pnpm, so resolveExtends could also fail in this case.

Workaround for now, use public-hoist-pattern[] for pnpm on userland.

Undeclaring paths alias causes a incorrect match result

Problem

I don't declare a path alias link '@libs/*', and when I use a matcher created by createPathsMatcher, it results

@libs/constants β†’ /cwd/@libs/constants

It doesn't make sense and should return undefined.

image

Expected behavior

It should return null if it matches nothing.

Minimal reproduction URL

https://stackblitz.com/edit/vitejs-vite-2pqdvg?file=index.mjs,tsconfig.json,package.json&terminal=dev

Version

4.7.2

Node.js version

18

Package manager

npm

Operating system

macOS

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

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 import-js/eslint-import-resolver-typescript#73

Feat: Async implementation

This lib is great, would there be a chance to support a fully async implementation even though ts doesn't directly support that AFAIK?

get-tsconfig output paths with extended tsconfig does not match tsc output

Problem

Here is a minimal reproduction of the issue described #60

https://github.com/matthewwolfe/get-tsconfig-bug

To reproduce:

  1. clone repo
  2. npm install
  3. npm run config
  4. npm run tsc:config
  5. compare output of paths

get-tsconfig output 4.7.1

{
  "path": "/Users/cn182266/tsconfig-example/tsconfig.json",
  "config": {
    "compilerOptions": {
      "declaration": true,
      "esModuleInterop": true,
      "experimentalDecorators": true,
      "forceConsistentCasingInFileNames": true,
      "jsx": "react",
      "lib": [
        "es2021",
        "dom"
      ],
      "module": "esnext",
      "moduleResolution": "node",
      "noEmit": true,
      "noImplicitAny": true,
      "preserveWatchOutput": true,
      "resolveJsonModule": true,
      "skipLibCheck": true,
      "strict": true,
      "strictNullChecks": true,
      "target": "es2019",
+     "paths": {
+       "@pkg/*": [
+         "./tsconfigs/*"
+       ]
+     },
      "baseUrl": "./src"
    },
    "include": [
      "src/**/*.ts",
      "src/**/*.tsx"
    ]
  }
}

get-tsconfig output 4.7.0

{
  "path": "/Users/cn182266/tsconfig-example/tsconfig.json",
  "config": {
    "compilerOptions": {
      "declaration": true,
      "esModuleInterop": true,
      "experimentalDecorators": true,
      "forceConsistentCasingInFileNames": true,
      "jsx": "react",
      "lib": [
        "es2021",
        "dom"
      ],
      "module": "esnext",
      "moduleResolution": "node",
      "noEmit": true,
      "noImplicitAny": true,
      "preserveWatchOutput": true,
      "resolveJsonModule": true,
      "skipLibCheck": true,
      "strict": true,
      "strictNullChecks": true,
      "target": "es2019",
+     "paths": {
+       "@pkg/*": [
+         "*"
+       ]
+     },
      "baseUrl": "./src"
    },
    "include": [
      "src/**/*.ts",
      "src/**/*.tsx"
    ]
  }
}

tsc output with --showConfig flag

{
    "compilerOptions": {
        "declaration": true,
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "forceConsistentCasingInFileNames": true,
        "jsx": "react",
        "lib": [
            "es2021",
            "dom"
        ],
        "module": "esnext",
        "moduleResolution": "node10",
        "noEmit": true,
        "noImplicitAny": true,
        "preserveWatchOutput": true,
        "resolveJsonModule": true,
        "skipLibCheck": true,
        "strict": true,
        "strictNullChecks": true,
        "target": "es2019",
+       "paths": {
+           "@pkg/*": [
+               "*"
+           ]
+       },
        "baseUrl": "./src"
    },
    "files": [
        "./src/index.ts"
    ],
    "include": [
        "src/**/*.ts",
        "src/**/*.tsx"
    ]
}

Expected behavior

The output paths of 4.7.1 should match 4.7.0 which matches the config that tsc produces with --showConfig

Minimal reproduction URL

https://github.com/matthewwolfe/get-tsconfig-bug

Version

4.7.1

Node.js version

18.16.0

Package manager

npm

Operating system

macOS

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

TYPO in project about

Problem

TypeScript `tsconfig.json` paser & paths resolver 

It should be parser.

TypeScript `tsconfig.json` parser & paths resolver 

Expected behavior

.

Minimal reproduction URL

.

Version

.

Node.js version

.

Package manager

N/A

Operating system

Linux

Contributions

  • I plan to open a pull request for this issue
  • I plan to make a financial contribution to this project

Support `"exports"` in package.json

In resolve-extends-path.ts, there's some custom logic that uses findUp to approximate the Node module resolution algorithm. It works for the classic style of module resolution, but doesn't implement the newer "exports" field in package.json. This causes failures in my use case (I have a monorepo with a package containing config files, and I want to do things like: "extends": "@my-worktree/configs/typescript/react", with @my-worktree/configs's package.json's "exports" mapping that to a tsconfig-react.json file in that package)

Would it be an option to use require.resolve as a primary or fallback mechanism in that extends resolution code, to offload the work to Node itself? (I'm guessing that's what TypeScript itself does - I've tested and confirmed that it respects the "exports" config when resolving extends-es)

v5 Roadmap

  • Rename parseTsconfig -> readTsconfig
  • If given a file path to getTsconfig, check if the found tsconfig's includes matches the file path
  • Move createPathsMatcher out to a different repo (TS resolver project?)

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').

Maximum call stack size exceeded when using extends from node_modules

Reproduction repository: https://github.com/kanoshin/get-tsconfig-repro

When tsconfig.json extends from npm package installed as a dependency, get-tsconfig fails with a Maximum call stack size exceeded exception:

{
    "extends": "@servicetitan/startup/tsconfig/base",
    "compilerOptions": {
        "module": "commonjs",
        "outDir": "dist",
        "rootDir": "src"
    },
    "include": ["src/**/*"],
    "exclude": ["src/**/__tests__/**/*"]
}

TypeScript allows you to extend config from an npm package, which is expected to work properly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.