axe-me / vite-plugin-node

Vite plugin to run your node dev server with HMR!
1k stars 48 forks source link

How to render some routes using Nest and some using Vite? #95

Open thgh opened 1 year ago

thgh commented 1 year ago

I have a Nest js application that routes some static assets to a create-react-app server. I would like to combine them and have everything run under Vite. The Nestjs example only renders the Nestjs application, it does not serve the js/html that was served before adding the plugin.

Is that possible?

cainrus commented 10 months ago

@thgh Add namespace for nest server. I hope that helps.

// ./server/bootstrap.ts
export async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api');
  return app;
}

Setup custom adapter

// vite.config.ts
import once from 'lodash/once';
import type { NestApplication } from '@nestjs/core';

const bootstrapOnce = once(
  async <T extends NestApplication>(init: () => Promise<T>): Promise<T> => {
    const app = await init();
    await app.init();
    return app;
  },
);

// ...
tsconfigPaths(),
    ...VitePluginNode({
      async adapter({ app, server, req, res, next }) {
        if (req.url.startsWith('/api/')) {
          bootstrapOnce(app).then((app: NestApplication) => {
            const instance = app.getHttpAdapter().getInstance();
            instance(req, res);
          });
        } else {
          next();
        }
      },
      appPath: './server/bootstrap.ts',
      tsCompiler: 'swc',
      exportName: 'bootstrap',
    }),