首页 > 解决方案 > 使用 TypeScript 的 Puppeteer 无法与 esModuleInterop 一起使用

问题描述

如果我尝试在 tsconfig.json 中使用带有 TypeScript 和 esModuleInterop=true 的 puppeteer,我会收到一条错误消息

puppeteer.launch 不是一个函数

如果我尝试导入 puppeteer

import * as puppeteer from "puppeteer";

现在我的问题是:这是预期的行为还是错误?

对我来说,只是将 esModuleInterop 设置为 false 没什么大不了的,但看起来很奇怪


小插件:

如果我手动更改puppeteer.launch()puppeteer.default.launch()index.js 它可以工作


链接:

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

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

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

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

标签: javascripttypescriptpuppeteertsc

解决方案


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


推荐阅读