Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(resolver): allow importing packages with non-index main script (#26692)

Dmitry Gozmanc9701795518b
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`);
+});