vite-plugin-node
vite-plugin-node copied to clipboard
Using this as part of a full stack dev server
Can I use this repo to run a full-stack dev server with vite?
I want to use this in conjunction with the react vite plugin and get it to server react from the root, and the express results from /api
Is there a way to config this to do that?
I think I might be having the same issue. When I add the config for vite-plugin-node, it compiles the server, but it stops compiling the client. Is there a way to have both in one project, or is the point of vite-plugin-node to have a project that ONLY acts as a server?
I have the same use case as well and I've found the following workaround:
...VitePluginNode({
// Instead of `adapter: "express"`, do this:
adapter({ app, req, res, next }) {
if (req.url.startsWith('/api/')) {
app(req, res);
} else {
next();
}
},
// other options...
}),
This essentially delegates all URLs starting with /api/
to the Node.js app (e.g. express) and anything else to the vanilla HTML serving logic in Vite during development. The example above is for express
, and you may need to change the adapter logic (in the if
-branch) accordingly (see https://github.com/axe-me/vite-plugin-node/tree/main/packages/vite-plugin-node/src/server for examples)
When running vite build
, the VitePluginNode
plugin sets build.ssr
, which causes Vite to build the server entry point only. The client code can be build by invoking vite build
again (as recommended by Vite docs) without the plugin into a different build.outDir
. This can be done by having two separate config files or conditional config. If your server need to serve the static files in production:
if (import.meta.env.PROD) {
app.use(express.static('relative/path/to/dist/client')); // or use path.join
// For single-page apps:
app.get('*', function (_, res) {
res.sendFile('relative/path/to/dist/client/index.html');
});
// For more customization and/or SSR: https://vitejs.dev/guide/ssr.html#building-for-production
app.listen(...);
}
For reference, my config can be found here, although it may contain many things that won't make sense in your setup (e.g. ssr.noExternal
).
closing cause there is a workaround. feel free to reopen.
I don't have plan so far to make it work with frontend ssr, since most of my projects have separate backend and frontend.
I recently started using vite-plugin-node to develop a nodejs server, it's an amazing plugin!
@yuchenshi Thank you for providing the solution. I also had a similar requirement - I needed to return some HTML frontend page, but wanted to using TypeScript too. This solved my problem.