环境要求

基础环境

  • Node.js 16+
  • npm 或 yarn
  • Vue 3.x
  • 支持ES6+的现代浏览器

开发工具推荐

  • VS Code + Vetur/Volar插件
  • Vue DevTools
  • Chrome DevTools

项目初始化

1. 创建项目目录

mkdir vue-ssr-demo
cd vue-ssr-demo
npm init -y

2. 安装核心依赖

# Vue 3 核心包
npm install vue@next

# SSR 相关
npm install @vue/server-renderer

# 构建工具
npm install vite @vitejs/plugin-vue

# 服务器
npm install express

3. 安装开发依赖

npm install -D @types/node

项目结构

vue-ssr-demo/
├── src/
│   ├── components/          # Vue组件
│   ├── pages/              # 页面组件
│   ├── router/             # 路由配置
│   ├── store/              # 状态管理
│   ├── app.js              # 应用入口
│   ├── entry-client.js     # 客户端入口
│   └── entry-server.js     # 服务端入口
├── server/
│   └── index.js            # Express服务器
├── public/                 # 静态资源
├── dist/                   # 构建输出
├── package.json
└── vite.config.js          # Vite配置

基础配置文件

package.json 脚本配置

{
  "scripts": {
    "dev": "node server/index.js",
    "build": "npm run build:client && npm run build:server",
    "build:client": "vite build --outDir dist/client",
    "build:server": "vite build --outDir dist/server --ssr src/entry-server.js",
    "serve": "NODE_ENV=production node server/index.js"
  }
}

vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html')
      }
    }
  }
})

开发环境配置

1. 热重载配置

// server/dev-server.js
import { createServer } from 'vite'

const vite = await createServer({
  server: { middlewareMode: true },
  appType: 'custom'
})

app.use(vite.ssrFixStacktrace)
app.use(vite.middlewares)

2. 开发代理配置

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true
      }
    }
  }
})

调试工具配置

1. Vue DevTools

// 在开发环境启用
if (process.env.NODE_ENV === 'development') {
  app.config.devtools = true
}

2. Source Map配置

// vite.config.js
export default defineConfig({
  build: {
    sourcemap: process.env.NODE_ENV === 'development'
  }
})

环境变量管理

.env 文件

# .env.development
VITE_API_URL=http://localhost:3001
VITE_APP_TITLE=Vue SSR Demo

# .env.production
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=Vue SSR App

使用环境变量

// 在代码中使用
const apiUrl = import.meta.env.VITE_API_URL
const appTitle = import.meta.env.VITE_APP_TITLE

常见问题解决

1. Node.js版本兼容性

# 检查Node.js版本
node --version

# 使用nvm管理版本
nvm install 18
nvm use 18

2. 依赖冲突解决

# 清理依赖
rm -rf node_modules package-lock.json
npm install

3. 端口占用问题

# 查找占用端口的进程
netstat -ano | findstr :3000

# 杀死进程
taskkill /PID <PID> /F

下一步

环境搭建完成后,我们将在下一章节学习如何创建基本的Vue SSR应用结构。