我试图在一个带有类型记录的SvelteKit项目中使用Puppeteer。我在用这个样板。
我做了:
npm install --save-dev puppeteer @types/puppeteer我创建了一个.ts文件并将:
import * as puppeteer from 'puppeteer';然后,我在我的一个.ts文件中导入了这个.svelte文件。
当我将应用程序部署到localhost以在浏览器中呈现上述.svelte文件时,将显示以下错误:
ReferenceError: process is not defined
at node_modules/pump/index.js (http://localhost:3000/node_modules/.vite/puppeteer.js?v=bf147010:16220:33)
at __require2 (http://localhost:3000/node_modules/.vite/chunk-UC7LELEO.js?v=bf147010:48:44)
at node_modules/get-stream/index.js (http://localhost:3000/node_modules/.vite/puppeteer.js?v=bf147010:16346:16)
at __require2 (http://localhost:3000/node_modules/.vite/chunk-UC7LELEO.js?v=bf147010:48:44)
at node_modules/extract-zip/index.js (http://localhost:3000/node_modules/.vite/puppeteer.js?v=bf147010:17730:21)
at __require2 (http://localhost:3000/node_modules/.vite/chunk-UC7LELEO.js?v=bf147010:48:44)
at node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserFetcher.js (http://localhost:3000/node_modules/.vite/puppeteer.js?v=bf147010:26161:41)
at __require2 (http://localhost:3000/node_modules/.vite/chunk-UC7LELEO.js?v=bf147010:48:44)
at node_modules/puppeteer/lib/cjs/puppeteer/node/Puppeteer.js (http://localhost:3000/node_modules/.vite/puppeteer.js?v=bf147010:27326:31)
at __require2 (http://localhost:3000/node_modules/.vite/chunk-UC7LELEO.js?v=bf147010:48:44)我该怎么解决?
所有这些都没有奏效:
@types/node。发布于 2022-03-31 14:53:53
你得到了一个SSR错误。您的.svelte文件中的代码首先在服务器上运行,而傀儡专家似乎无法在服务器上旋转虚拟浏览器实例。
解决这个问题的最简单方法是检查您是否在浏览器中运行。您可以通过从browser导入$app/env变量来实现这一点。
import { browser } from "$app/env";
if (browser) {
import('puppeteer').then(puppeteer => {
// Do your stuff
})
}如果您想导出模块(或其他任何东西),您可以导出一个空变量,并在以后给它赋值。
import { browser } from "$app/env";
export let puppeteer;
if (browser) {
import('puppeteer').then(module => {
puppeteer = module
};
}您也可以考虑禁用SSR,并从本质上制造SPA。然而,它是在SvelteKit文档中非常气馁,所以我建议您不要这样做。
https://stackoverflow.com/questions/70820709
复制相似问题