Vue3
This tutorial will guide you through building a Vue3 SSR application from scratch using the Esmx framework. We'll demonstrate how to create a server-side rendered application through a complete example.
Project Structure
First, let's understand the basic project structure:
1.
2├── package.json # Project configuration file defining dependencies and scripts
3├── tsconfig.json # TypeScript configuration file with compilation options
4└── src # Source code directory
5 ├── app.vue # Main application component defining page structure and interactions
6 ├── create-app.ts # Vue instance factory for application initialization
7 ├── entry.client.ts # Client entry file handling browser-side rendering
8 ├── entry.node.ts # Node.js server entry file for dev environment configuration
9 └── entry.server.ts # Server entry file handling SSR rendering logic
Project Configuration
package.json
Create the package.json
file to configure project dependencies and scripts:
package.json
1{
2 "name": "ssr-demo-vue3",
3 "version": "1.0.0",
4 "type": "module",
5 "private": true,
6 "scripts": {
7 "dev": "esmx dev",
8 "build": "npm run build:dts && npm run build:ssr",
9 "build:ssr": "esmx build",
10 "preview": "esmx preview",
11 "start": "NODE_ENV=production node dist/index.mjs",
12 "build:dts": "vue-tsc --declaration --emitDeclarationOnly --outDir dist/src"
13 },
14 "dependencies": {
15 "@esmx/core": "*"
16 },
17 "devDependencies": {
18 "@esmx/rspack-vue": "*",
19 "@types/node": "22.8.6",
20 "@vue/server-renderer": "^3.5.13",
21 "typescript": "^5.7.3",
22 "vue": "^3.5.13",
23 "vue-tsc": "^2.1.6"
24 }
25}
After creating the package.json
file, install project dependencies using any of these commands:
1pnpm install
2# or
3yarn install
4# or
5npm install
This will install all required dependencies including Vue3, TypeScript, and SSR-related packages.
tsconfig.json
Create the tsconfig.json
file to configure TypeScript compilation options:
tsconfig.json
1{
2 "compilerOptions": {
3 "module": "ESNext",
4 "moduleResolution": "node",
5 "isolatedModules": true,
6 "resolveJsonModule": true,
7
8 "target": "ESNext",
9 "lib": ["ESNext", "DOM"],
10
11 "strict": true,
12 "skipLibCheck": true,
13 "types": ["@types/node"],
14
15 "experimentalDecorators": true,
16 "allowSyntheticDefaultImports": true,
17
18 "baseUrl": ".",
19 "paths": {
20 "ssr-demo-vue3/src/*": ["./src/*"],
21 "ssr-demo-vue3/*": ["./*"]
22 }
23 },
24 "include": ["src"],
25 "exclude": ["dist", "node_modules"]
26}
Source Code Structure
app.vue
Create the main application component src/app.vue
using Vue3's Composition API:
src/app.vue
1<template>
2 <div>
3 <h1><a href="https://www.esmnext.com/guide/frameworks/vue3.html" target="_blank">Esmx Quick Start</a></h1>
4 <time :datetime="time">{{ time }}</time>
5 </div>
6</template>
7
8<script setup lang="ts">
9/**
10 * @file Example Component
11 * @description Displays a page title with auto-updating time, demonstrating basic Esmx framework functionality
12 */
13
14import { onMounted, onUnmounted, ref } from 'vue';
15
16// Current time, updates every second
17const time = ref(new Date().toISOString());
18let timer: NodeJS.Timeout;
19
20onMounted(() => {
21 timer = setInterval(() => {
22 time.value = new Date().toISOString();
23 }, 1000);
24});
25
26onUnmounted(() => {
27 clearInterval(timer);
28});
29</script>
create-app.ts
Create src/create-app.ts
to handle Vue application instance creation:
src/create-app.ts
1/**
2 * @file Vue Instance Creation
3 * @description Handles creation and configuration of Vue application instance
4 */
5
6import { createSSRApp } from 'vue';
7import App from './app.vue';
8
9export function createApp() {
10 const app = createSSRApp(App);
11 return {
12 app
13 };
14}
entry.client.ts
Create the client entry file src/entry.client.ts
:
src/entry.client.ts
1/**
2 * @file Client Entry File
3 * @description Handles client-side interaction logic and dynamic updates
4 */
5
6import { createApp } from './create-app';
7
8// Create Vue instance
9const { app } = createApp();
10
11// Mount Vue instance
12app.mount('#app');
entry.node.ts
Create entry.node.ts
to configure the development environment and server startup:
src/entry.node.ts
1/**
2 * @file Node.js Server Entry File
3 * @description Configures development environment and server startup, providing SSR runtime
4 */
5
6import http from 'node:http';
7import type { EsmxOptions } from '@esmx/core';
8
9export default {
10 /**
11 * Configures development environment application creator
12 * @description Creates and configures Rspack application instance for development builds and HMR
13 * @param esmx Esmx framework instance providing core functionality
14 * @returns Configured Rspack application instance with HMR support
15 */
16 async devApp(esmx) {
17 return import('@esmx/rspack-vue').then((m) =>
18 m.createRspackVue3App(esmx, {
19 config(context) {
20 // Custom Rspack compilation configuration can be added here
21 }
22 })
23 );
24 },
25
26 /**
27 * Configures and starts HTTP server
28 * @description Creates HTTP server instance with Esmx middleware for SSR requests
29 * @param esmx Esmx framework instance providing middleware and rendering
30 */
31 async server(esmx) {
32 const server = http.createServer((req, res) => {
33 // Process requests with Esmx middleware
34 esmx.middleware(req, res, async () => {
35 // Perform server-side rendering
36 const rc = await esmx.render({
37 params: { url: req.url }
38 });
39 res.end(rc.html);
40 });
41 });
42
43 server.listen(3000, () => {
44 console.log('Server started: http://localhost:3000');
45 });
46 }
47} satisfies EsmxOptions;
This file serves as the entry point for development environment configuration and server startup, containing two core functions:
devApp
: Creates and configures the Rspack application instance for development with HMR support, using createRspackVue3App
specifically for Vue3.
server
: Creates and configures the HTTP server with Esmx middleware for SSR requests.
entry.server.ts
Create the server-side rendering entry file src/entry.server.ts
:
src/entry.server.ts
1/**
2 * @file Server-Side Rendering Entry File
3 * @description Handles SSR process, HTML generation and resource injection
4 */
5
6import type { RenderContext } from '@esmx/core';
7import { renderToString } from '@vue/server-renderer';
8import { createApp } from './create-app';
9
10export default async (rc: RenderContext) => {
11 // Create Vue application instance
12 const { app } = createApp();
13
14 // Generate page content using Vue's renderToString
15 const html = await renderToString(app, {
16 importMetaSet: rc.importMetaSet
17 });
18
19 // Commit dependency collection to ensure all required resources are loaded
20 await rc.commit();
21
22 // Generate complete HTML structure
23 rc.html = `<!DOCTYPE html>
24<html lang="en">
25<head>
26 ${rc.preload()}
27 <title>Esmx Quick Start</title>
28 ${rc.css()}
29</head>
30<body>
31 <div id="app">${html}</div>
32 ${rc.importmap()}
33 ${rc.moduleEntry()}
34 ${rc.modulePreload()}
35</body>
36</html>
37`;
38};
Running the Project
After completing the file configurations, use these commands to run the project:
- Development mode:
- Build the project:
- Production environment:
You've now successfully created a Vue3 SSR application using the Esmx framework! Visit http://localhost:3000 to see the result.