Skip to content

Commit 8cc77e5

Browse files
authored
fix: should add index main file when redirect.js.path set to false (#1198)
1 parent 627aa10 commit 8cc77e5

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

packages/core/src/config.ts

Lines changed: 14 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,
@@ -1436,6 +1437,19 @@ const composeBundlelessExternalConfig = (
14361437
} else {
14371438
// 1. js files hit JS_EXTENSIONS_PATTERN,./foo ->./foo.mjs
14381439
if (jsRedirectExtension) {
1440+
// If the import path refers to a directory,
1441+
// it most likely actually refers to a `index.*` file due to Node's module resolution.
1442+
// When redirect.js.path is set to false, index should still be added before adding extension.
1443+
// When redirect.js.path is true, the resolver directly generate correct resolvedRequest with index appended.
1444+
if (
1445+
!jsRedirectPath &&
1446+
(await isDirectory(
1447+
join(dirname(issuer), resolvedRequest),
1448+
))
1449+
) {
1450+
// This uses `/` instead of `path.join` here because `join` removes potential "./" prefixes
1451+
resolvedRequest = `${resolvedRequest.replace(/\/+$/, '')}/index`;
1452+
}
14391453
resolvedRequest = `${resolvedRequest}${jsExtension}`;
14401454
}
14411455
}

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)