Jerry
Jerry

Reputation: 85

Puppeteer with TypeScript not working with esModuleInterop

If I'm trying to use puppeteer with TypeScript and esModuleInterop=true set in tsconfig.json I get an error saying

puppeteer.launch is not a function

if I try to import puppeteer with

import * as puppeteer from "puppeteer";

Now to my question: Is this intended behavior or a bug?

For me, it's not a big deal to just set esModuleInterop to false, but it seems odd


Small add-on:

if I manually change puppeteer.launch() to puppeteer.default.launch() in index.js it works


Links:

tsconfig.json: https://pastebin.com/6xvkfJg2

package.json: https://pastebin.com/ViwfMwyQ

index.ts: https://pastebin.com/GtHuiHSJ

index.js: https://pastebin.com/TzeCDiGn

Upvotes: 2

Views: 3246

Answers (2)

Thiago Anuszkiewicz
Thiago Anuszkiewicz

Reputation: 23

Try this:

import { launch } from 'puppeteer';

Then all you have to do is:

const browser = await launch();

Upvotes: 1

AMakarov
AMakarov

Reputation: 339

Use import puppeteer from 'puppeteer' syntax or get rid of esModuleInterop flag.

A long time ago, when the typescript language was developed, the ECMAScript modules specification was still in draft. Moreover, the direction of the typescript as a language was slightly different: a typescript team did not hesitate to add features non-compatible with ES. One of these features is modules syntax.

import * as smth from 'smth' is a valid typescript code, but not ECMAScript code.
import smth from 'smth' is a valid ECMAScript code but is not valid typescript construction.

Flag esModuleInterop literally means "we are going to use ECMAScript imports in our code".
Now, when people have adopted and loved ES modules syntax this flag is arguably the standard.

A more detailed article

Upvotes: 1

Related Questions