Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion docs/src/test-typescript-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`, `jsx`, `jsxFactory`, `jsxFragmentFactory`, `jsxImportSource`, `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`, `useDefineForClassFields`, `references` and `extends`. The `target` option is only used to determine `useDefineForClassFields`.

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.

Expand Down Expand Up @@ -86,6 +86,20 @@ Playwright compiles JSX in `.tsx` and `.jsx` files according to the `jsx`, `jsxF
}
```

### tsconfig class fields

Playwright compiles TypeScript class fields according to the `useDefineForClassFields` option in the `tsconfig.json`. Just like `tsc`, when it is not specified, it is enabled for `ES2022` and later targets, and when `target` is not specified.

With `useDefineForClassFields` enabled, class fields follow the JavaScript semantics, so field initializers run before the constructor body and can not access constructor parameter properties. Disable it to keep the legacy TypeScript semantics.

```json title="tsconfig.json"
{
"compilerOptions": {
"useDefineForClassFields": false
}
}
```

### 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.
Expand Down
33 changes: 22 additions & 11 deletions packages/playwright/src/transform/babelBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type JsxOptions = {
jsxFragmentFactory?: string;
jsxImportSource?: string;
};
export type BabelTransformFunction = (code: string, filename: string, isModule: boolean, pluginsSuffix: BabelPlugin[], jsx?: JsxOptions) => BabelFileResult | null;
export type BabelTransformFunction = (code: string, filename: string, isModule: boolean, pluginsSuffix: BabelPlugin[], useDefineForClassFields: boolean, jsx?: JsxOptions) => BabelFileResult | null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder whether it's time to define TransformOptions and use it across babelBundle and transform?


const nodeMajorVersion = +process.versions.node.split('.')[0];

Expand All @@ -57,39 +57,50 @@ function jsxPlugin(jsx: JsxOptions | undefined): [any, any] {
}];
}

function babelTransformOptions(isTypeScript: boolean, isModule: boolean, pluginsEpilogue: [string, any?][], jsx?: JsxOptions): TransformOptions {
function babelTransformOptions(isTypeScript: boolean, isModule: boolean, pluginsEpilogue: [string, any?][], useDefineForClassFields: boolean, jsx?: JsxOptions): TransformOptions {
const plugins = [
[require('@babel/plugin-syntax-import-attributes'), { deprecatedAssertSyntax: true }],
];

if (isTypeScript) {
plugins.push(
// Strip "declare" class fields before these plugins run:
// Strip "declare" class fields, and uninitialized ones that tsc omits without
// "useDefineForClassFields", before these plugins run:
// - plugin-proposal-decorators
// - plugin-transform-class-properties
// - plugin-transform-private-methods
// See https://github.com/microsoft/playwright/issues/38586
[
(): PluginObj => ({
name: 'strip-declare-class-fields',
name: 'strip-type-only-class-fields',
visitor: {
Class(path) {
for (const member of path.get('body.body')) {
if (member.isClassProperty() && member.node.declare)
if (!member.isClassProperty())
continue;
const { declare, value, decorators } = member.node;
if (declare || (!useDefineForClassFields && !value && !decorators?.length))
member.remove();
}
}
}
})
],
[require('@babel/plugin-proposal-decorators'), { version: '2023-05' }],
[require('@babel/plugin-transform-class-properties')],
);
// With "useDefineForClassFields", Node defines class fields natively.
if (!useDefineForClassFields) {
plugins.push(
[require('@babel/plugin-transform-class-properties')],
[require('@babel/plugin-transform-private-methods')],
);
}
plugins.push(
[require('@babel/plugin-transform-class-static-block')],
[require('@babel/plugin-transform-numeric-separator')],
[require('@babel/plugin-transform-logical-assignment-operators')],
[require('@babel/plugin-transform-nullish-coalescing-operator')],
[require('@babel/plugin-transform-optional-chaining')],
[require('@babel/plugin-transform-private-methods')],
[require('@babel/plugin-syntax-json-strings')],
[require('@babel/plugin-syntax-optional-catch-binding')],
[require('@babel/plugin-syntax-async-generators')],
Expand Down Expand Up @@ -163,7 +174,7 @@ function babelTransformOptions(isTypeScript: boolean, isModule: boolean, plugins
setPublicClassFields: true,
},
presets: isTypeScript ? [
[require('@babel/preset-typescript'), { onlyRemoveTypeImports: false }],
[require('@babel/preset-typescript'), { onlyRemoveTypeImports: false, allowDeclareFields: useDefineForClassFields }],
] : [],
plugins: [
...plugins,
Expand All @@ -180,21 +191,21 @@ 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?][], jsx?: JsxOptions): BabelFileResult | null {
export function babelTransform(code: string, filename: string, isModule: boolean, pluginsEpilogue: [string, any?][], useDefineForClassFields: boolean, jsx?: JsxOptions): BabelFileResult | null {
if (isTransforming)
return null;

// Prevent reentry while requiring plugins lazily.
isTransforming = true;
try {
const options = babelTransformOptions(isTypeScript(filename), isModule, pluginsEpilogue, jsx);
const options = babelTransformOptions(isTypeScript(filename), isModule, pluginsEpilogue, useDefineForClassFields, jsx);
return babel.transform(code, { filename, ...options });
} finally {
isTransforming = false;
}
}

export function babelParse(code: string, filename: string, isModule: boolean): babel.ParseResult {
const options = babelTransformOptions(isTypeScript(filename), isModule, []);
const options = babelTransformOptions(isTypeScript(filename), isModule, [], true);
return babel.parse(code, { filename, ...options })!;
}
20 changes: 16 additions & 4 deletions packages/playwright/src/transform/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type ParsedTsConfigData = {
paths: { key: string, values: string[] }[];
allowJs: boolean;
jsx?: JsxOptions;
useDefineForClassFields?: boolean;
};
const cachedTSConfigs = new Map<string, ParsedTsConfigData[]>();

Expand Down Expand Up @@ -86,9 +87,16 @@ function validateTsConfig(tsconfig: LoadedTsConfig): ParsedTsConfigData {
jsxFragmentFactory: tsconfig.jsxFragmentFactory,
jsxImportSource: tsconfig.jsxImportSource,
} : undefined,
useDefineForClassFields: tsconfig.useDefineForClassFields ?? (tsconfig.target ? targetUsesDefineForClassFields(tsconfig.target) : undefined),
};
}

function targetUsesDefineForClassFields(target: string): boolean {
const normalized = target.toLowerCase();
const year = normalized.match(/^es(\d{4})$/)?.[1];
return normalized === 'esnext' || (!!year && +year >= 2022);
}

function loadAndValidateTsconfigsForFile(file: string): ParsedTsConfigData[] {
if (_singleTSConfigPath && !_singleTSConfig)
_singleTSConfig = loadTsConfig(_singleTSConfigPath).map(validateTsConfig);
Expand Down Expand Up @@ -221,8 +229,11 @@ 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 jsx = loadAndValidateTsconfigsForFile(filename).find(tsconfig => tsconfig.jsx)?.jsx;
const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, jsx);
const tsconfigs = loadAndValidateTsconfigsForFile(filename);
const jsx = tsconfigs.find(tsconfig => tsconfig.jsx)?.jsx;
// Without "target", tsc defaults to the latest one, which defines class fields.
const useDefineForClassFields = tsconfigs.find(tsconfig => tsconfig.useDefineForClassFields !== undefined)?.useDefineForClassFields ?? true;
const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, useDefineForClassFields, jsx);
const { cachedCode, addToCache, serializedCache } = cc.getFromCompilationCache(filename, hash, moduleUrl);
if (cachedCode !== undefined)
return { code: cachedCode, serializedCache };
Expand All @@ -232,21 +243,22 @@ 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, jsx);
const babelResult = babelTransform(originalCode, filename, !!moduleUrl, pluginsEpilogue, useDefineForClassFields, jsx);
if (!babelResult?.code)
return { code: originalCode, serializedCache };
const { code, map } = babelResult;
const added = addToCache!(code, map);
return { code, serializedCache: added.serializedCache };
}

function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], jsx: JsxOptions | undefined): string {
function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], useDefineForClassFields: boolean, 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(useDefineForClassFields ? 'define' : 'assign')
.update(jsx ? JSON.stringify(jsx) : '')
.digest('hex');
return hash;
Expand Down
8 changes: 8 additions & 0 deletions packages/playwright/src/transform/tsconfig-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ interface TsConfig {
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
target?: string;
useDefineForClassFields?: boolean;
};
references?: { path: string }[];
}
Expand All @@ -57,6 +59,8 @@ export interface LoadedTsConfig {
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
target?: string;
useDefineForClassFields?: boolean;
}

const jsxOptionNames = ['jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource'] as const;
Expand Down Expand Up @@ -139,6 +143,10 @@ function innerLoadTsConfig(
if (parsedConfig.compilerOptions?.[name] !== undefined)
result[name] = parsedConfig.compilerOptions[name];
}
if (parsedConfig.compilerOptions?.target !== undefined)
result.target = parsedConfig.compilerOptions.target;
if (parsedConfig.compilerOptions?.useDefineForClassFields !== undefined)
result.useDefineForClassFields = parsedConfig.compilerOptions.useDefineForClassFields;
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:
Expand Down
40 changes: 40 additions & 0 deletions tests/playwright-test/babel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ test('should treat enums equally', async ({ runInlineTest }) => {
test('should be able to access |this| inside class properties', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21794' });
const result = await runInlineTest({
'tsconfig.json': `{ "compilerOptions": { "useDefineForClassFields": false } }`,
'example.spec.ts': `
import { test, expect } from '@playwright/test';

Expand All @@ -127,6 +128,45 @@ test('should be able to access |this| inside class properties', async ({ runInli
expect(result.passed).toBe(1);
});

for (const [compilerOptions, define] of [

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So many tests for such a small feature??

[{}, true],
[{ target: 'ES2022' }, true],
[{ target: 'ES2021' }, false],
[{ target: 'ES2021', useDefineForClassFields: true }, true],
[{ target: 'ESNext', useDefineForClassFields: false }, false],
] as const) {
test(`should ${define ? 'define' : 'assign'} class fields with ${JSON.stringify(compilerOptions)}`, async ({ runInlineTest }) => {
const result = await runInlineTest({
'tsconfig.json': JSON.stringify({ compilerOptions }),
'example.spec.ts': `
import { test, expect } from '@playwright/test';

class Base {
redeclared = 'base';
setterCalls: string[] = [];
set overridden(value: string) { this.setterCalls.push(value); }
}

class Derived extends Base {
redeclared: string;
overridden = 'derived';
fromParameter = this.parameter + '-field';
constructor(private parameter: string) { super(); }
}

test('works', () => {
const derived = new Derived('parameter');
expect(derived.redeclared).toBe(${define ? 'undefined' : `'base'`});
expect(derived.setterCalls).toEqual(${define ? '[]' : `['derived']`});
expect(derived.fromParameter).toBe(${define ? `'undefined-field'` : `'parameter-field'`});
});
`,
});
expect(result.exitCode).toBe(0);
expect(result.passed).toBe(1);
});
}

test('should work with |const| Type Parameters', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21900' });
const result = await runInlineTest({
Expand Down