From c9701795518b9c68388e4fe5b9d9ca00b9c0d376 Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Thu, 24 Aug 2023 14:09:00 -0700 Subject: [PATCH] fix(resolver): allow importing packages with non-index main script (#26692) Regressed in https://github.com/microsoft/playwright/pull/23254. Fixes #26650. --- packages/playwright-test/src/util.ts | 7 ++++- tests/playwright-test/resolver.spec.ts | 37 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/playwright-test/src/util.ts b/packages/playwright-test/src/util.ts index 1ef5c61452..f825c145c7 100644 --- a/packages/playwright-test/src/util.ts +++ b/packages/playwright-test/src/util.ts @@ -342,8 +342,13 @@ export function resolveImportSpecifierExtension(resolved: string): string | unde } break; // Do not try '' when a more specific extesion like '.jsx' matched. } - // try directory imports last + if (dirExists(resolved)) { + // If we import a package, let Node.js figure out the correct import based on package.json. + if (fileExists(path.join(resolved, 'package.json'))) + return resolved; + + // Otherwise, try to find a corresponding index file. const dirImport = path.join(resolved, 'index'); return resolveImportSpecifierExtension(dirImport); } diff --git a/tests/playwright-test/resolver.spec.ts b/tests/playwright-test/resolver.spec.ts index 3101bcd7a9..56b3da0a56 100644 --- a/tests/playwright-test/resolver.spec.ts +++ b/tests/playwright-test/resolver.spec.ts @@ -505,3 +505,40 @@ test('should support extends in tsconfig.json', async ({ runInlineTest }) => { expect(result.passed).toBe(1); expect(result.exitCode).toBe(0); }); + +test('should import packages with non-index main script through path resolver', async ({ runInlineTest }) => { + const result = await runInlineTest({ + 'app/pkg/main.ts': ` + export const foo = 42; + `, + 'app/pkg/package.json': ` + { "main": "main.ts" } + `, + 'package.json': ` + { "name": "example-project" } + `, + 'playwright.config.ts': ` + export default {}; + `, + 'tsconfig.json': `{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "app/*": ["app/*"], + }, + }, + }`, + 'example.spec.ts': ` + import { foo } from 'app/pkg'; + import { test, expect } from '@playwright/test'; + test('test', ({}) => { + console.log('foo=' + foo); + }); + `, + }); + + expect(result.exitCode).toBe(0); + expect(result.passed).toBe(1); + expect(result.output).not.toContain(`find module`); + expect(result.output).toContain(`foo=42`); +});