Skip to content

Commit 7bb3965

Browse files
committed
fix: should add index main file when redirect.js.path set to false
1 parent a14f8d4 commit 7bb3965

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

packages/core/src/config.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import {
6363
calcLongestCommonPath,
6464
checkMFPlugin,
6565
getAbsolutePath,
66+
isDirectory,
6667
isEmptyObject,
6768
isIntermediateOutputFormat,
6869
isObject,
@@ -1434,6 +1435,17 @@ const composeBundlelessExternalConfig = (
14341435
}
14351436
}
14361437
} else {
1438+
// If the import path refers to a directory,
1439+
// it most likely actually refers to a `index.*` file due to Node's module resolution.
1440+
// When redirect.js.path is set to false, index should still be added before adding extension.
1441+
// When redirect.js.path is true, the resolver directly generate correct resolvedRequest with index appended.
1442+
if (
1443+
!jsRedirectPath &&
1444+
(await isDirectory(join(dirname(issuer), resolvedRequest)))
1445+
) {
1446+
// This uses `/` instead of `path.join` here because `join` removes potential "./" prefixes
1447+
resolvedRequest = `${resolvedRequest.replace(/\/+$/, '')}/index`;
1448+
}
14371449
// 1. js files hit JS_EXTENSIONS_PATTERN,./foo ->./foo.mjs
14381450
if (jsRedirectExtension) {
14391451
resolvedRequest = `${resolvedRequest}${jsExtension}`;

packages/core/src/utils/helper.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,3 +246,12 @@ const windowsSlashRegex = /\\/g;
246246
export function normalizeSlash(p: string): string {
247247
return p.replace(windowsSlashRegex, '/');
248248
}
249+
250+
export async function isDirectory(filePath: string): Promise<boolean> {
251+
try {
252+
const stat = await fsP.stat(filePath);
253+
return stat.isDirectory();
254+
} catch {
255+
return false;
256+
}
257+
}

tests/integration/redirect/js.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,11 @@ test('redirect.js.path false', async () => {
5353
import { bar } from "@/bar";
5454
import { foo } from "@/foo";
5555
import { baz } from "~/baz";
56-
import { bar as external_bar_js_bar } from "./bar.js";
56+
import { bar as index_js_bar } from "./bar/index.js";
5757
import { foo as external_foo_js_foo } from "./foo.js";
5858
export * from "./.hidden.js";
59-
export * from "./.hidden-folder.js";
60-
const src = lodash.toUpper(lodash_merge(external_foo_js_foo) + external_bar_js_bar + foo + bar + baz + typeof prettier.version);
59+
export * from "./.hidden-folder/index.js";
60+
const src = lodash.toUpper(lodash_merge(external_foo_js_foo) + index_js_bar + foo + bar + baz + typeof prettier.version);
6161
export { src as default };
6262
"
6363
`);

0 commit comments

Comments
 (0)