From 7d2642d26480b212b926b41d6e6f4dc4ab38beee Mon Sep 17 00:00:00 2001 From: Scott Anderson Date: Wed, 28 Sep 2022 13:07:39 +0100 Subject: [PATCH] fix: resolve modules if folder contains a package.json file 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 --- src/index.ts | 8 ++++++-- tests/withPaths/index.ts | 3 +++ tests/withPaths/module/module.d.ts | 1 + tests/withPaths/module/package.json | 5 +++++ 4 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 tests/withPaths/module/module.d.ts create mode 100644 tests/withPaths/module/package.json diff --git a/src/index.ts b/src/index.ts index b8e1707..5ce76fe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' @@ -267,7 +271,7 @@ function getMappedPath( const originalExtensions = extensions extensions = ['', ...extensions] - let paths: string[] | undefined = [] + let paths: Array | undefined = [] if (RELATIVE_PATH_PATTERN.test(source)) { const resolved = path.resolve(path.dirname(file), source) @@ -283,7 +287,7 @@ function getMappedPath( ]), ) .flat(2) - .filter(isFile) + .filter(path => isFile(path) || isModule(path)) } if (retry && paths.length === 0) { diff --git a/tests/withPaths/index.ts b/tests/withPaths/index.ts index 8d011e9..594e79d 100644 --- a/tests/withPaths/index.ts +++ b/tests/withPaths/index.ts @@ -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' diff --git a/tests/withPaths/module/module.d.ts b/tests/withPaths/module/module.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/tests/withPaths/module/module.d.ts @@ -0,0 +1 @@ +export {} diff --git a/tests/withPaths/module/package.json b/tests/withPaths/module/package.json new file mode 100644 index 0000000..f69fe0b --- /dev/null +++ b/tests/withPaths/module/package.json @@ -0,0 +1,5 @@ +{ + "type": "commonjs", + "typings": "./module.d.ts", + "private": true +}