Reputation: 591
I'm trying to use Puppeteer in a SvelteKit project with Typescript. I'm using this boilerplate.
I did:
npm install --save-dev puppeteer @types/puppeteer
I created a .ts
file and put:
import * as puppeteer from 'puppeteer';
Then I imported that .ts
file in one of my .svelte
files.
When I deployed my app to localhost
to render said .svelte
file in my browser, this error is displayed:
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)
How do I solve?
None of these have worked:
@types/node
.tsconfig.js
.Upvotes: 0
Views: 902
Reputation: 1866
You're getting a SSR error. The code in your .svelte
files is run first in the server, and it seems puppeteer can't spin up a virtual browser instance on the server.
The easiest way to fix this is to check if you're running in the browser. You do this by importing the browser
variable from $app/env
:
import { browser } from "$app/env";
if (browser) {
import('puppeteer').then(puppeteer => {
// Do your stuff
})
}
If you want to export the module (or anything else), you can export an empty variable and assign it a value later.
import { browser } from "$app/env";
export let puppeteer;
if (browser) {
import('puppeteer').then(module => {
puppeteer = module
};
}
You can also consider disabling SSR and making essentially a SPA. However, it is heavily discouraged in the SvelteKit docs, so I would advise against it.
Upvotes: 1