Home > Blockchain >  Process is not defined Svelte/Vite (using node-imap)
Process is not defined Svelte/Vite (using node-imap)

Time:07-11

I am trying to use the library node-imap in my SvelteKit/Vite application. I import the library with import * as Imap from "imap";. When I try running my application, I get the following error:

process is not defined
ReferenceError: process is not defined
    at node_modules/.pnpm/[email protected]/node_modules/utf7/utf7.js (http://localhost:3000/node_modules/.vite/deps/imap.js?v=e5efcf87:944:20)
    at __require (http://localhost:3000/node_modules/.vite/deps/chunk-OL3AADLO.js?v=e5efcf87:9:50)
    at node_modules/.pnpm/[email protected]/node_modules/imap/lib/Connection.js (http://localhost:3000/node_modules/.vite/deps/imap.js?v=e5efcf87:5022:16)
    at __require (http://localhost:3000/node_modules/.vite/deps/chunk-OL3AADLO.js?v=e5efcf87:9:50)
    at http://localhost:3000/node_modules/.vite/deps/imap.js?v=e5efcf87:6690:20

The problem seems to be that Vite/Svelte does not support process, rather using import.meta.env for environment variables. How can I get the library working?

CodePudding user response:

You just have to make sure the code only runs on the server, as the client will not have access to process.

Endpoints will run only on the server while load will run both on client and server.

E.g. this endpoint code would be valid:

import type { RequestHandler } from '@sveltejs/kit';

export const get: RequestHandler = () => {
    return {
        body: { env: process.env }
    }
}
  • Related