Skip to content

expose context parameter for server.ssrLoadModule #10396

@await-ovo

Description

@await-ovo

Description

As a developer using Vite server-side rendering. I use ssrLoadModule to transform and load source code. This is very convenient (thanks for this awesome project~).

Since I want to use the edge runtime API to run the source code, I was hoping we could expose the context for ViteDevServer.ssrLoadModule so I could inject the Edge Runtime primitives into the scope of the code execution function:

I see that there is already a context parameter for the ssrLoadModule method in vite/src/node/ssr/ssrModuleLoader.ts, so it just needs to expose the context in the server's ssrModuleLoader, as follows:

  ssrLoadModule(
    url: string,
    opts?: { 
       fixStacktrace?: boolean,
       context: Record<string, any>, 
   }
  ): Promise<Record<string, any>>

In addition to this case, I think supporting custom contexts should also make ssrLoadModule more flexible.

I would be happy to send a pr if I could do so ~ Thanks a lot!

Suggested solution

Finally, when custom SSR context are needed, we can do something like this:

import { createServer as createViteServer } from 'vite';

const server = await createViteServer({
  server: { middlewareMode: true },
  appType: 'custom',
});

const { render } = await server.ssrLoadModule('/src/entry-server.tsx', {
  context: {
    fetch: customFetchPolyfill,
    URLPattern: urlpattern - polyfill,
  },
});

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions