john
Oct 24 2020 at 20:10 GMT
I am using Puppeteer with TypeScript and when I try to evaluate an async function on a page:
await page.evaluate(async function() {
// code to execute on the page
})
I get the following error:
Error: Evaluation failed: ReferenceError: __awaiter is not defined
What is causing this? How can I fix the issue?
Travis
Oct 24 2020 at 20:30 GMT
It looks like TypeScript is transpiling your code to an older version of JavaScript and so the async function is converted to code that is using the __awaiter
util.
However, Puppeteer serializes the function passed to page.evaluate
into a string and tries to execute it in the browser.
Since the __awaiter
helper was not sent to the browser, you get a ReferenceError
.
The solution is to not transpile your code to something old like ES5 as it's not really necessary; Puppeteer runs in one of the latest versions of Chrome, which supports modern JavaScript features, and this is also the case for a modern version of NodeJS.
So, to make the TypeScript compiler not transform async functions, you need to change the compilerOptions.target
in tsconfig.json
to at least ES2017
:
{
"compilerOptions": {
"target": "ES2017",
...
}
}