Skip to content

Commit

Permalink
fix: resolve modules if folder contains a package.json file
Browse files Browse the repository at this point in the history
getMappedPath only resolves to files that exist. This does not
work when a TSConfig path alias resolves to a module folder
containing built assets, and described by a package.json, e.g.
foo/dist.

If the tsconfig path is mapped to a folder, then getMappedPath
returns undefined as the folder is not a file. However, in somes
cases it is ok for this to resolve as the package.json contains
a `typings` entry that references a .d.ts file, which is
correctly handled by enhanced-resolve
  • Loading branch information
sanderson-ut committed Sep 28, 2022
1 parent 85f64d0 commit 7d2642d
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/index.ts
Expand Up @@ -250,6 +250,10 @@ const isFile = (path?: string | undefined): path is string => {
}
}

const isModule = (path?: string | undefined): path is string => {
return !!path && isFile(`${path}/package.json`)
}

/**
* @param {string} source the module to resolve; i.e './some-module'
* @param {string} file the importing file's full path; i.e. '/usr/local/bin/file.js'
Expand All @@ -267,7 +271,7 @@ function getMappedPath(
const originalExtensions = extensions
extensions = ['', ...extensions]

let paths: string[] | undefined = []
let paths: Array<string | undefined> | undefined = []

if (RELATIVE_PATH_PATTERN.test(source)) {
const resolved = path.resolve(path.dirname(file), source)
Expand All @@ -283,7 +287,7 @@ function getMappedPath(
]),
)
.flat(2)
.filter(isFile)
.filter(path => isFile(path) || isModule(path))
}

if (retry && paths.length === 0) {
Expand Down
3 changes: 3 additions & 0 deletions tests/withPaths/index.ts
Expand Up @@ -10,6 +10,9 @@ import 'folder/tsxImportee'
import 'folder/subfolder/tsImportee'
import 'folder/subfolder/tsxImportee'

// import module with typings set in package.json
import 'folder/module'

// import from node_module
import 'typescript'
import 'dummy.js'
1 change: 1 addition & 0 deletions tests/withPaths/module/module.d.ts
@@ -0,0 +1 @@
export {}
5 changes: 5 additions & 0 deletions tests/withPaths/module/package.json
@@ -0,0 +1,5 @@
{
"type": "commonjs",
"typings": "./module.d.ts",
"private": true
}

0 comments on commit 7d2642d

Please sign in to comment.