[BUG] Script in index.ts runs too late
See original GitHub issueContext:
- Playwright Version: @playwright/experimental-ct-react@1.26.0
- Browser: All
System:
- OS: macOS 12.6
- Memory: 390.20 MB / 16.00 GB
Binaries:
- Node: 18.9.0 - ~/.nvm/versions/node/v18.9.0/bin/node
- npm: 8.19.1 - ~/.nvm/versions/node/v18.9.0/bin/npm
Languages:
- Bash: 3.2.57 - /bin/bash
Code Snippet
<!-- /playwright/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Testing Page</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/playwright/index.ts"></script>
</body>
</html>
/** /playwright/index.ts **/
// Import styles, initialize component theme here.
(self as Mutable<typeof self>)._clientConfig = {
debugEnabled: true,
}
export {};
/** The tested component module */
/**
* This could be for example Redux store init. It's common to init the store with extra middleware for debugging.
* This line of code runs before the script from /playwright/index.ts, so it fails on _clientConfig to be undefined.
*/
const store = self._clientConfig.debugEnabled
? () => ({
/** todo add debug middleware... */
value: 'value',
})
: () => ({
value: 'value',
});
export const Component = () => {
return (
<>
<div>{store().value}</div>
</>
);
}
Runtime output
The error in the browser console during the test:

Output bundle
Line 568 is the code from the tested component reading the self._clientConfig.
Line 581 is the definition of self._clientConfig:

Describe the bug
The content of index.ts is merged with the components js bundle, but instead of at the beginning of the file, it appears at the end it appears after the tested components code. This behavior means we cannot set domain-specific globals for the browser and the tested component fails on self._clientConfig to be undefined if read by zero indent code.
Based on the docs https://playwright.dev/docs/test-components#playwrightindexts, I guess it should run before the component definition code.
Steps to reproduce
- Clone repo https://github.com/RichardJuchelka/Playwright-script_in_index_ts_runs_too_late
npm run install-projectnpm run playwright-debug- Open the browser devtools, and see the error in the console tab.
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)

Top Related StackOverflow Question
So the issue is that we generate a following snippet:
And esbuild is moving the imports up, because they need to be leading. As a result, component’s inline code runs before the index.ts.
Yes, that’s a workaround. Another one is to move the config setup code into its own module and reference it before index.ts script: