Skip to content

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

fix(test-runner): compile jsx according to tsconfig options (#42972)

Pavel Feldman75cbb778956b
diff --git a/docs/src/test-typescript-js.md b/docs/src/test-typescript-js.md
index 6a83c06117..d607830af6 100644
--- a/docs/src/test-typescript-js.md
+++ b/docs/src/test-typescript-js.md
@@ -28,7 +28,7 @@ npx tsc -p tsconfig.json --noEmit -w
## tsconfig.json
-Playwright will pick up `tsconfig.json` for each source file it loads. Note that Playwright **only supports** the following tsconfig options: `allowJs`, `baseUrl`, `paths`, `references` and `extends`.
+Playwright will pick up `tsconfig.json` for each source file it loads. Note that Playwright **only supports** the following tsconfig options: `allowJs`, `baseUrl`, `paths`, `jsx`, `jsxFactory`, `jsxFragmentFactory`, `jsxImportSource`, `references` and `extends`.
We recommend setting up a separate `tsconfig.json` in the tests directory so that you can change some preferences specifically for the tests. Here is an example directory structure.
@@ -73,6 +73,19 @@ test('example', async ({ page }) => {
});
```
+### tsconfig JSX options
+
+Playwright compiles JSX in `.tsx` and `.jsx` files according to the `jsx`, `jsxFactory`, `jsxFragmentFactory` and `jsxImportSource` options in the `tsconfig.json`. When `jsx` is not specified, or is set to `preserve` or `react-native`, Playwright uses the automatic runtime from `react/jsx-runtime`.
+
+```json title="tsconfig.json"
+{
+ "compilerOptions": {
+ "jsx": "react-jsx",
+ "jsxImportSource": "preact"
+ }
+}
+```
+
### tsconfig resolution
By default, Playwright will look up a closest tsconfig for each imported file by going up the directory structure and looking for `tsconfig.json` or `jsconfig.json`. This way, you can create a `tests/tsconfig.json` file that will be used only for your tests and Playwright will pick it up automatically.
diff --git a/packages/playwright/jsx-runtime.js b/packages/playwright/jsx-runtime.js
deleted file mode 100644
index ff3d79e34e..0000000000
--- a/packages/playwright/jsx-runtime.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-function jsx(type, props, key) {
- return {
- __pw_type: 'jsx',
- type,
- props,
- key,
- };
-}
-
-function jsxs(type, props, key) {
- return {
- __pw_type: 'jsx',
- type,
- props,
- key,
- };
-}
-
-// this is used in <></> notation
-const Fragment = { __pw_jsx_fragment: true };
-
-module.exports = {
- Fragment,
- jsx,
- jsxs,
-};
diff --git a/packages/playwright/jsx-runtime.mjs b/packages/playwright/jsx-runtime.mjs
deleted file mode 100644
index 1dfd5835aa..0000000000
--- a/packages/playwright/jsx-runtime.mjs
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import jsxRuntime from './jsx-runtime.js';
-
-export const jsx = jsxRuntime.jsx;
-export const jsxs = jsxRuntime.jsxs;
-export const Fragment = jsxRuntime.Fragment;
diff --git a/packages/playwright/package.json b/packages/playwright/package.json
index 462d41c287..0193257e5f 100644
--- a/packages/playwright/package.json
+++ b/packages/playwright/package.json
@@ -23,11 +23,6 @@
"./lib/program": "./lib/program.js",
"./lib/runner": "./lib/runner/index.js",
"./lib/transform/babelBundle": "./lib/transform/babelBundle.js",
- "./jsx-runtime": {
- "import": "./jsx-runtime.mjs",
- "require": "./jsx-runtime.js",
- "default": "./jsx-runtime.js"
- },
"./lib/util": "./lib/util.js",
"./types/test": {
"types": "./types/test.d.ts"
diff --git a/packages/playwright/src/common/configLoader.ts b/packages/playwright/src/common/configLoader.ts
index 6e2fa63afb..5e74dc254a 100644
--- a/packages/playwright/src/common/configLoader.ts
+++ b/packages/playwright/src/common/configLoader.ts
@@ -117,8 +117,7 @@ export async function loadConfig(location: ConfigLocation, overrides?: ConfigCLI
// 3. Load transform options from the playwright config.
const external = userConfig.build?.external || [];
- const jsxImportSource = path.dirname(require.resolve('playwright'));
- await setTransformConfig({ external, jsxImportSource });
+ await setTransformConfig({ external });
if (!overrides?.tsconfig)
await setSingleTSConfig(fullConfig?.singleTSConfigPath);
diff --git a/packages/playwright/src/transform/babelBundle.ts b/packages/playwright/src/transform/babelBundle.ts
index 096de75e1a..69309367e3 100644
--- a/packages/playwright/src/transform/babelBundle.ts
+++ b/packages/playwright/src/transform/babelBundle.ts
@@ -30,11 +30,34 @@ export type { NodePath, PluginObj, types as T } from '@babel/core';
export type { BabelAPI } from '@babel/helper-plugin-utils';
export type BabelPlugin = [string, any?];
-export type BabelTransformFunction = (code: string, filename: string, isModule: boolean, pluginsSuffix: BabelPlugin[], jsxImportSource?: string) => BabelFileResult | null;
+export type JsxOptions = {
+ jsx: string;
+ jsxFactory?: string;
+ jsxFragmentFactory?: string;
+ jsxImportSource?: string;
+};
+export type BabelTransformFunction = (code: string, filename: string, isModule: boolean, pluginsSuffix: BabelPlugin[], jsx?: JsxOptions) => BabelFileResult | null;
const nodeMajorVersion = +process.versions.node.split('.')[0];
-function babelTransformOptions(isTypeScript: boolean, isModule: boolean, pluginsEpilogue: [string, any?][], jsxImportSource?: string): TransformOptions {
+function jsxPlugin(jsx: JsxOptions | undefined): [any, any] {
+ if (jsx?.jsx === 'react') {
+ return [require('@babel/plugin-transform-react-jsx'), {
+ throwIfNamespace: false,
+ runtime: 'classic',
+ pragma: jsx.jsxFactory,
+ pragmaFrag: jsx.jsxFragmentFactory,
+ }];
+ }
+ const plugin = jsx?.jsx === 'react-jsxdev' ? require('@babel/plugin-transform-react-jsx/lib/development') : require('@babel/plugin-transform-react-jsx');
+ return [plugin, {
+ throwIfNamespace: false,
+ runtime: 'automatic',
+ importSource: jsx?.jsxImportSource,
+ }];
+}
+
+function babelTransformOptions(isTypeScript: boolean, isModule: boolean, pluginsEpilogue: [string, any?][], jsx?: JsxOptions): TransformOptions {
const plugins = [
[require('@babel/plugin-syntax-import-attributes'), { deprecatedAssertSyntax: true }],
];
@@ -94,11 +117,7 @@ function babelTransformOptions(isTypeScript: boolean, isModule: boolean, plugins
}
// Support JSX/TSX at all times, regardless of the file extension.
- plugins.push([require('@babel/plugin-transform-react-jsx'), {
- throwIfNamespace: false,
- runtime: 'automatic',
- ...(jsxImportSource ? { importSource: jsxImportSource } : {}),
- }]);
+ plugins.push(jsxPlugin(jsx));
if (!isModule) {
plugins.push([require('@babel/plugin-transform-modules-commonjs')]);
@@ -145,14 +164,14 @@ function isTypeScript(filename: string) {
return filename.endsWith('.ts') || filename.endsWith('.tsx') || filename.endsWith('.mts') || filename.endsWith('.cts');
}
-export function babelTransform(code: string, filename: string, isModule: boolean, pluginsEpilogue: [string, any?][], jsxImportSource?: string): BabelFileResult | null {
+export function babelTransform(code: string, filename: string, isModule: boolean, pluginsEpilogue: [string, any?][], jsx?: JsxOptions): BabelFileResult | null {
if (isTransforming)
return null;
// Prevent reentry while requiring plugins lazily.
isTransforming = true;
try {
- const options = babelTransformOptions(isTypeScript(filename), isModule, pluginsEpilogue, jsxImportSource);
+ const options = babelTransformOptions(isTypeScript(filename), isModule, pluginsEpilogue, jsx);
return babel.transform(code, { filename, ...options });
} finally {
isTransforming = false;
diff --git a/packages/playwright/src/transform/transform.ts b/packages/playwright/src/transform/transform.ts
index 076c3b5940..63bb52fdd4 100644
--- a/packages/playwright/src/transform/transform.ts
+++ b/packages/playwright/src/transform/transform.ts
@@ -28,7 +28,7 @@ import * as esmLoaderSync from './esmLoaderSync';
import { addHook } from './pirates';
import { PortTransport } from './portTransport';
-import type { BabelPlugin, BabelTransformFunction } from './babelBundle';
+import type { BabelPlugin, BabelTransformFunction, JsxOptions } from './babelBundle';
import type { Location } from '../../types/testReporter';
import type { LoadedTsConfig } from './tsconfig-loader';
import type { Matcher } from '../util';
@@ -40,12 +40,12 @@ type ParsedTsConfigData = {
pathsBase?: string;
paths: { key: string, values: string[] }[];
allowJs: boolean;
+ jsx?: JsxOptions;
};
const cachedTSConfigs = new Map<string, ParsedTsConfigData[]>();
export type TransformConfig = {
external: string[];
- jsxImportSource?: string;
};
let _transformConfig: TransformConfig = {
@@ -79,7 +79,13 @@ function validateTsConfig(tsconfig: LoadedTsConfig): ParsedTsConfigData {
return {
allowJs: !!tsconfig.allowJs,
pathsBase,
- paths: Object.entries(tsconfig.paths?.mapping || {}).map(([key, values]) => ({ key, values })).concat(pathsFallback)
+ paths: Object.entries(tsconfig.paths?.mapping || {}).map(([key, values]) => ({ key, values })).concat(pathsFallback),
+ jsx: tsconfig.jsx ? {
+ jsx: tsconfig.jsx.toLowerCase(),
+ jsxFactory: tsconfig.jsxFactory,
+ jsxFragmentFactory: tsconfig.jsxFragmentFactory,
+ jsxImportSource: tsconfig.jsxImportSource,
+ } : undefined,
};
}
@@ -215,7 +221,8 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE &&
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some(f => filename.startsWith(f));
const pluginsEpilogue = hasPreprocessor ? [[process.env.PW_TEST_SOURCE_TRANSFORM!]] as BabelPlugin[] : [];
- const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue);
+ const jsx = loadAndValidateTsconfigsForFile(filename).find(tsconfig => tsconfig.jsx)?.jsx;
+ const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, jsx);
const { cachedCode, addToCache, serializedCache } = cc.getFromCompilationCache(filename, hash, moduleUrl);
if (cachedCode !== undefined)
return { code: cachedCode, serializedCache };
@@ -225,7 +232,7 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
process.env.BROWSERSLIST_IGNORE_OLD_DATA = 'true';
const { babelTransform }: { babelTransform: BabelTransformFunction } = require(libPath('transform', 'babelBundle'));
- const babelResult = babelTransform(originalCode, filename, !!moduleUrl, pluginsEpilogue, _transformConfig.jsxImportSource);
+ const babelResult = babelTransform(originalCode, filename, !!moduleUrl, pluginsEpilogue, jsx);
if (!babelResult?.code)
return { code: originalCode, serializedCache };
const { code, map } = babelResult;
@@ -233,13 +240,14 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
return { code, serializedCache: added.serializedCache };
}
-function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[]): string {
+function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], jsx: JsxOptions | undefined): string {
const hash = crypto.createHash('sha1')
.update(isModule ? 'esm' : 'no_esm')
.update(content)
.update(filePath)
.update(version)
.update(pluginsEpilogue.map(p => p[0]).join(','))
+ .update(jsx ? JSON.stringify(jsx) : '')
.digest('hex');
return hash;
}
diff --git a/packages/playwright/src/transform/tsconfig-loader.ts b/packages/playwright/src/transform/tsconfig-loader.ts
index 9ae8544bee..1d040edc39 100644
--- a/packages/playwright/src/transform/tsconfig-loader.ts
+++ b/packages/playwright/src/transform/tsconfig-loader.ts
@@ -37,6 +37,10 @@ interface TsConfig {
paths?: { [key: string]: Array<string> };
strict?: boolean;
allowJs?: boolean;
+ jsx?: string;
+ jsxFactory?: string;
+ jsxFragmentFactory?: string;
+ jsxImportSource?: string;
};
references?: { path: string }[];
}
@@ -49,8 +53,14 @@ export interface LoadedTsConfig {
};
absoluteBaseUrl?: string;
allowJs?: boolean;
+ jsx?: string;
+ jsxFactory?: string;
+ jsxFragmentFactory?: string;
+ jsxImportSource?: string;
}
+const jsxOptionNames = ['jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource'] as const;
+
export function loadTsConfig(configPath: string): LoadedTsConfig[] {
try {
const references: LoadedTsConfig[] = [];
@@ -107,6 +117,10 @@ function innerLoadTsConfig(
if (parsedConfig.compilerOptions?.allowJs !== undefined)
result.allowJs = parsedConfig.compilerOptions.allowJs;
+ for (const name of jsxOptionNames) {
+ if (parsedConfig.compilerOptions?.[name] !== undefined)
+ result[name] = parsedConfig.compilerOptions[name];
+ }
if (parsedConfig.compilerOptions?.paths !== undefined) {
// We must store pathsBasePath from the config that defines "paths" and later resolve
// based on this absolute path, when no "baseUrl" is specified. See tsc for reference:
diff --git a/tests/playwright-test/loader.spec.ts b/tests/playwright-test/loader.spec.ts
index cca5bbf037..e3f6502d96 100644
--- a/tests/playwright-test/loader.spec.ts
+++ b/tests/playwright-test/loader.spec.ts
@@ -469,8 +469,28 @@ test('should load web server w/o esm loader in esm module', async ({ runInlineTe
expect(result.output).toContain('NODE_OPTIONS undefined');
});
+const jsxRuntimeFiles = (...names: string[]) => Object.assign({ 'package.json': JSON.stringify({ name: 'test-project' }) }, ...names.map(name => ({
+ [`node_modules/${name}/package.json`]: JSON.stringify({
+ name,
+ exports: {
+ './jsx-runtime': './jsx-runtime.js',
+ './jsx-dev-runtime': './jsx-dev-runtime.js',
+ },
+ }),
+ [`node_modules/${name}/jsx-runtime.js`]: `
+ exports.jsx = (type, props) => ({ runtime: '${name}', type, props });
+ exports.jsxs = exports.jsx;
+ exports.Fragment = '${name}-fragment';
+ `,
+ [`node_modules/${name}/jsx-dev-runtime.js`]: `
+ exports.jsxDEV = (type, props, key, isStatic, source) => ({ runtime: '${name}-dev', type, props, fileName: source.fileName });
+ exports.Fragment = '${name}-fragment';
+ `,
+})));
+
test('should load a jsx/tsx files', async ({ runInlineTest }) => {
const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('react'),
'a.spec.tsx': `
import { test, expect } from '@playwright/test';
const component = () => <div></div>;
@@ -492,6 +512,7 @@ test('should load a jsx/tsx files', async ({ runInlineTest }) => {
test('should load a jsx/tsx files in ESM mode', async ({ runInlineTest }) => {
const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('react'),
'package.json': JSON.stringify({
type: 'module'
}),
@@ -518,25 +539,20 @@ test('should load a jsx/tsx files in ESM mode', async ({ runInlineTest }) => {
expect(exitCode).toBe(0);
});
-test('should load jsx with top-level component', async ({ runInlineTest }) => {
+test('should use react/jsx-runtime when tsconfig does not configure jsx', async ({ runInlineTest }) => {
const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('react'),
'a.spec.tsx': `
import { test, expect } from '@playwright/test';
- const component = <div>Hello <span>world</span></div>;
test('succeeds', () => {
- expect(component).toEqual({
- __pw_type: 'jsx',
+ expect(<div>Hello <span>world</span><>!</></div>).toEqual({
+ runtime: 'react',
type: 'div',
props: {
children: [
'Hello ',
- {
- __pw_type: 'jsx',
- type: 'span',
- props: {
- children: 'world'
- },
- }
+ { runtime: 'react', type: 'span', props: { children: 'world' } },
+ { runtime: 'react', type: 'react-fragment', props: { children: '!' } },
]
},
});
@@ -547,8 +563,130 @@ test('should load jsx with top-level component', async ({ runInlineTest }) => {
expect(exitCode).toBe(0);
});
+test('should respect jsxImportSource from tsconfig', async ({ runInlineTest }) => {
+ const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('my-jsx'),
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx', jsxImportSource: 'my-jsx' } }),
+ 'a.spec.tsx': `
+ import { test, expect } from '@playwright/test';
+ test('succeeds', () => {
+ expect(<div><>!</></div>).toEqual({
+ runtime: 'my-jsx',
+ type: 'div',
+ props: { children: { runtime: 'my-jsx', type: 'my-jsx-fragment', props: { children: '!' } } },
+ });
+ });
+ `,
+ 'b.spec.jsx': `
+ import { test, expect } from '@playwright/test';
+ test('succeeds', () => {
+ expect(<span />).toEqual({ runtime: 'my-jsx', type: 'span', props: {} });
+ });
+ `,
+ });
+ expect(passed).toBe(2);
+ expect(exitCode).toBe(0);
+});
+
+test('should respect jsxImportSource from tsconfig in ESM mode', async ({ runInlineTest }) => {
+ const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('my-jsx'),
+ 'package.json': JSON.stringify({ type: 'module' }),
+ 'playwright.config.ts': `export default {};`,
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx', jsxImportSource: 'my-jsx' } }),
+ 'a.spec.tsx': `
+ import { test, expect } from '@playwright/test';
+ test('succeeds', () => {
+ expect(<div />).toEqual({ runtime: 'my-jsx', type: 'div', props: {} });
+ });
+ `,
+ });
+ expect(passed).toBe(1);
+ expect(exitCode).toBe(0);
+});
+
+test('should respect classic jsx factory from tsconfig', async ({ runInlineTest }) => {
+ const { exitCode, passed } = await runInlineTest({
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react', jsxFactory: 'h', jsxFragmentFactory: 'Frag' } }),
+ 'a.spec.tsx': `
+ import { test, expect } from '@playwright/test';
+ const h = (type, props, ...children) => ({ factory: 'h', type, props, children });
+ const Frag = 'frag';
+ test('succeeds', () => {
+ expect(<div id="a">Hello <>world</></div>).toEqual({
+ factory: 'h',
+ type: 'div',
+ props: { id: 'a' },
+ children: ['Hello ', { factory: 'h', type: 'frag', props: null, children: ['world'] }],
+ });
+ });
+ `,
+ });
+ expect(passed).toBe(1);
+ expect(exitCode).toBe(0);
+});
+
+test('should respect react-jsxdev from tsconfig', async ({ runInlineTest }) => {
+ const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('my-jsx'),
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsxdev', jsxImportSource: 'my-jsx' } }),
+ 'a.spec.tsx': `
+ import { test, expect } from '@playwright/test';
+ test('succeeds', () => {
+ expect(<div />).toEqual({ runtime: 'my-jsx-dev', type: 'div', props: {}, fileName: expect.stringContaining('a.spec.tsx') });
+ });
+ `,
+ });
+ expect(passed).toBe(1);
+ expect(exitCode).toBe(0);
+});
+
+test('should respect jsx options from tsconfig references and extends', async ({ runInlineTest }) => {
+ const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('my-jsx'),
+ 'tsconfig.json': JSON.stringify({ files: [], references: [{ path: './tsconfig.node.json' }, { path: './tsconfig.app.json' }] }),
+ 'tsconfig.node.json': JSON.stringify({ compilerOptions: { strict: true } }),
+ 'tsconfig.app.json': JSON.stringify({ extends: './tsconfig.base.json', compilerOptions: { jsxImportSource: 'my-jsx' } }),
+ 'tsconfig.base.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx', jsxImportSource: 'other-jsx' } }),
+ 'a.spec.tsx': `
+ import { test, expect } from '@playwright/test';
+ test('succeeds', () => {
+ expect(<div />).toEqual({ runtime: 'my-jsx', type: 'div', props: {} });
+ });
+ `,
+ });
+ expect(passed).toBe(1);
+ expect(exitCode).toBe(0);
+});
+
+test('should recompile when tsconfig jsx options change', async ({ runInlineTest }) => {
+ const files = {
+ ...jsxRuntimeFiles('jsx-a', 'jsx-b'),
+ 'a.spec.tsx': `
+ import { test, expect } from '@playwright/test';
+ test('succeeds', () => {
+ console.log('%%' + (<div />).runtime);
+ });
+ `,
+ };
+ const result1 = await runInlineTest({
+ ...files,
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx', jsxImportSource: 'jsx-a' } }),
+ });
+ expect(result1.exitCode).toBe(0);
+ expect(result1.outputLines).toEqual(['jsx-a']);
+
+ const result2 = await runInlineTest({
+ ...files,
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx', jsxImportSource: 'jsx-b' } }),
+ });
+ expect(result2.exitCode).toBe(0);
+ expect(result2.outputLines).toEqual(['jsx-b']);
+});
+
test('should load a jsx/tsx files with fragments', async ({ runInlineTest }) => {
const { exitCode, passed } = await runInlineTest({
+ ...jsxRuntimeFiles('react'),
'helper.tsx': `
export const component = () => <><div></div></>;
export function add(a: number, b: number) {