Vue2

This tutorial will guide you through building a Vue2 SSR application with Esmx from the ground up. We'll demonstrate how to create a server-side rendered application using the Esmx framework 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 logic
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 setup
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-vue2",
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    "typescript": "^5.7.3",
21    "vue": "^2.7.16",
22    "vue-server-renderer": "^2.7.16",
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 Vue2, TypeScript, and SSR-related packages.

tsconfig.json

Create the tsconfig.json file to configure TypeScript compilation:

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-vue2/src/*": ["./src/*"],
21            "ssr-demo-vue2/*": ["./*"]
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 <script setup> syntax:

src/app.vue
1<template>
2    <div id="app">
3        <h1><a href="https://www.esmnext.com/guide/frameworks/vue2.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 to demonstrate Esmx framework basics
12 */
13
14import { onMounted, onUnmounted, ref } from 'vue';
15
16// Current time updating 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 Creates and configures Vue application instances
4 */
5
6import Vue from 'vue';
7import App from './app.vue';
8
9export function createApp() {
10    const app = new Vue({
11        render: (h) => h(App)
12    });
13    return {
14        app
15    };
16}

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 for development environment configuration:

src/entry.node.ts
1/**
2 * @file Node.js server entry file
3 * @description Configures development environment and server startup for 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.createRspackVue2App(esmx, {
19                config(context) {
20                    // Custom Rspack compilation configuration
21                }
22            })
23        );
24    },
25
26    /**
27     * Configures and starts HTTP server
28     * @description Creates HTTP server 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:

  1. devApp: Creates and configures the Rspack application instance for development with HMR support using createRspackVue2App.
  2. server: Creates and configures the HTTP server with Esmx middleware for SSR requests.

entry.server.ts

Create the SSR 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 { createRenderer } from 'vue-server-renderer';
8import { createApp } from './create-app';
9
10// Create renderer
11const renderer = createRenderer();
12
13export default async (rc: RenderContext) => {
14    // Create Vue application instance
15    const { app } = createApp();
16
17    // Generate page content with Vue's renderToString
18    const html = await renderer.renderToString(app, {
19        importMetaSet: rc.importMetaSet
20    });
21
22    // Commit dependency collection to ensure all required resources are loaded
23    await rc.commit();
24
25    // Generate complete HTML structure
26    rc.html = `<!DOCTYPE html>
27<html lang="en">
28<head>
29    ${rc.preload()}
30    <title>Esmx Quick Start</title>
31    ${rc.css()}
32</head>
33<body>
34    ${html}
35    ${rc.importmap()}
36    ${rc.moduleEntry()}
37    ${rc.modulePreload()}
38</body>
39</html>
40`;
41};

Running the Project

After completing the configuration, use these commands to run the project:

  1. Development mode:
1npm run dev
  1. Build project:
1npm run build
  1. Production run:
1npm run start

Congratulations! You've successfully created a Vue2 SSR application with Esmx. Visit http://localhost:3000 to see the result.