Vue | Vite | Express |
---|---|---|
2.7.15 |
4.4.5 |
4.18.2 |
Here's an example for running a Vue2 + Typescript frontend with Vite & SSR. When implementing this for my own project I really struggled to find (any) examples, so hopefully this helps someone in the same situation I was in!
Vue2 + Typescript:
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
/**
* Yaaay, full Typescript-compliant Vue SFC!
*/
});
</script>
Vite SSR setup:
import { createRenderer } from 'vue-server-renderer';
import { createApp } from './main';
const renderer = createRenderer();
export async function render({ url }) {
const { app } = createApp();
const appHtml = await renderer.renderToString(app);
return { appHtml };
}
app.get('*', (req, res, next) => {
// Vite assumes entry-server.js's exported `render` function calls the
// appropriate framework SSR APIs: e.g. VueServerRenderer.renderToString()
const { appHtml } = await render({
url: req.originalUrl,
});
});
# Clone this gist from GitHub
$ git clone [email protected]:076813c15d273e904501e285209f3815 vue2-vite-ts-ssr && cd ./vue2-vite-ts-ssr
# Install the dependencies
$ npm ci
# Runs client-only SPA with hot reloading
$ npm run dev:client
# Runs server-only SSR with hot reloading
$ npm run dev:server
# Build for production
$ npm run build
# Runs client-only SPA with vite preview
$ npm run preview:client
# Runs server-only SSR with Express
$ npm run preview:server
Hello James,
Thank you for this very useful piece of code.
I've been able to add vue-router to it without much trouble.
I'm now trying to handle meta tags, page title and initial_state but I cant manage to make it work.
When I'm creating the renderer like this :
With this index.html
Only the
div#app
seems to be rendered and the outer tags (<title>, <meta..>,...) are ignored.Of course i'm calling the renderToString with the proper context:
Can you help me with this ? It's really the last piece missing
Thanks :)