第2课:Vue3 环境搭建

【腾讯云】语音识别准确率高,支持多语种,多场景,限时特惠,最低14.9元起

推广

【腾讯云】语音识别准确率高,支持多语种,多场景,限时特惠,最低14.9元起

Vue3 环境搭建

系统要求

必需环境

  • Node.js:14.18+ 或 16+(推荐使用LTS版本)
  • npm:6+ 或 yarn:1.22+ 或 pnpm:7+
  • 现代浏览器:Chrome 87+、Firefox 78+、Safari 14+

推荐环境

  • 操作系统:Windows 10+、macOS 10.15+、Ubuntu 18.04+
  • 内存:8GB以上
  • 存储:至少2GB可用空间

Node.js安装

方法一:官方安装包

  1. 访问 Node.js官网
  2. 下载LTS版本(推荐)
  3. 运行安装程序,按默认设置安装

方法二:包管理器安装

Windows (Chocolatey)

# 安装Chocolatey
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

# 安装Node.js
choco install nodejs

macOS (Homebrew)

# 安装Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# 安装Node.js
brew install node

Ubuntu/Debian

# 使用NodeSource仓库
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

# 或使用snap
sudo snap install node --classic

方法三:版本管理器(推荐)

nvm (Node Version Manager)

# 安装nvm (Linux/macOS)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# 重启终端或执行
source ~/.bashrc

# 安装最新LTS版本
nvm install --lts
nvm use --lts

# 设置默认版本
nvm alias default node

nvm-windows

# 下载并安装nvm-windows
# https://github.com/coreybutler/nvm-windows/releases

# 安装Node.js
nvm install lts
nvm use lts

验证安装

node --version    # 应显示 v18.x.x 或更高版本
npm --version     # 应显示 8.x.x 或更高版本

包管理器选择

npm(默认)

# 查看版本
npm --version

# 设置国内镜像
npm config set registry https://registry.npmmirror.com

# 全局安装包
npm install -g @vue/cli

yarn(推荐)

# 安装yarn
npm install -g yarn

# 查看版本
yarn --version

# 设置国内镜像
yarn config set registry https://registry.npmmirror.com

# 全局安装包
yarn global add @vue/cli

pnpm(高性能)

# 安装pnpm
npm install -g pnpm

# 查看版本
pnpm --version

# 设置国内镜像
pnpm config set registry https://registry.npmmirror.com

# 全局安装包
pnpm add -g @vue/cli

创建Vue3项目

方法一:create-vue(推荐)

# 使用npm
npm create vue@latest my-vue-project

# 使用yarn
yarn create vue my-vue-project

# 使用pnpm
pnpm create vue my-vue-project

创建过程中的选项:

✔ Project name: … my-vue-project
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add an End-to-End Testing Solution? › No
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes

方法二:Vue CLI

# 安装Vue CLI
npm install -g @vue/cli

# 创建项目
vue create my-vue-project

# 或使用图形界面
vue ui

方法三:Vite

# 使用Vite模板
npm create vite@latest my-vue-project -- --template vue

# 或使用TypeScript模板
npm create vite@latest my-vue-project -- --template vue-ts

项目结构解析

标准Vue3项目结构

my-vue-project/
├── public/                 # 静态资源
│   ├── favicon.ico
│   └── index.html
├── src/                    # 源代码
│   ├── assets/            # 资源文件
│   ├── components/        # 组件
│   ├── router/            # 路由配置
│   ├── stores/            # 状态管理
│   ├── views/             # 页面组件
│   ├── App.vue            # 根组件
│   └── main.js            # 入口文件
├── tests/                 # 测试文件
├── .gitignore            # Git忽略文件
├── index.html            # HTML模板
├── package.json          # 项目配置
├── README.md             # 项目说明
└── vite.config.js        # Vite配置

关键文件说明

package.json

{
  "name": "my-vue-project",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test:unit": "vitest",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore",
    "format": "prettier --write src/"
  },
  "dependencies": {
    "vue": "^3.3.0",
    "vue-router": "^4.2.0",
    "pinia": "^2.1.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.2.0",
    "vite": "^4.3.0",
    "vitest": "^0.32.0",
    "eslint": "^8.39.0",
    "prettier": "^2.8.8"
  }
}

main.js

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.mount('#app')

App.vue

<template>
  <div id="app">
    <nav>
      <RouterLink to="/">Home</RouterLink>
      <RouterLink to="/about">About</RouterLink>
    </nav>
    <RouterView />
  </div>
</template>

<script>
import { RouterLink, RouterView } from 'vue-router'

export default {
  components: {
    RouterLink,
    RouterView
  }
}
</script>

<style scoped>
nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
  text-decoration: none;
  margin-right: 10px;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

开发工具配置

VS Code配置

必装插件

{
  "recommendations": [
    "Vue.volar",              // Vue3语言支持
    "Vue.vscode-typescript-vue-plugin", // TypeScript支持
    "bradlc.vscode-tailwindcss",        // Tailwind CSS
    "esbenp.prettier-vscode",           // 代码格式化
    "dbaeumer.vscode-eslint",           // 代码检查
    "formulahendry.auto-rename-tag",    // 自动重命名标签
    "christian-kohler.path-intellisense" // 路径智能提示
  ]
}

工作区设置

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "vue"
  ],
  "vetur.validation.template": false,
  "vetur.validation.script": false,
  "vetur.validation.style": false
}

WebStorm配置

  1. 安装Vue.js插件
  2. 启用TypeScript支持
  3. 配置ESLint和Prettier
  4. 设置代码模板

Chrome DevTools

# 安装Vue DevTools扩展
# Chrome Web Store搜索 "Vue.js devtools"

项目启动和构建

开发环境

# 进入项目目录
cd my-vue-project

# 安装依赖
npm install

# 启动开发服务器
npm run dev

# 浏览器访问 http://localhost:5173

生产构建

# 构建生产版本
npm run build

# 预览构建结果
npm run preview

# 运行测试
npm run test:unit

# 代码检查
npm run lint

# 代码格式化
npm run format

Vite配置

基础配置

// 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')
    }
  },
  server: {
    port: 3000,
    open: true,
    cors: true
  },
  build: {
    outDir: 'dist',
    sourcemap: false,
    minify: 'terser'
  }
})

环境变量配置

# .env.development
VITE_API_BASE_URL=http://localhost:8080/api
VITE_APP_TITLE=Vue3 开发环境

# .env.production
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=Vue3 生产环境

使用环境变量:

// 在组件中使用
console.log(import.meta.env.VITE_API_BASE_URL)
console.log(import.meta.env.VITE_APP_TITLE)

代码规范配置

ESLint配置

// .eslintrc.cjs
module.exports = {
  root: true,
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/eslint-config-prettier'
  ],
  parserOptions: {
    ecmaVersion: 'latest'
  },
  rules: {
    'vue/multi-word-component-names': 'off',
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  }
}

Prettier配置

{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "none",
  "printWidth": 80,
  "bracketSpacing": true,
  "arrowParens": "avoid"
}

Git Hooks配置

# 安装husky和lint-staged
npm install --save-dev husky lint-staged

# 初始化husky
npx husky install

# 添加pre-commit钩子
npx husky add .husky/pre-commit "npx lint-staged"
// package.json
{
  "lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  }
}

常见问题解决

1. Node.js版本问题

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

# 如果版本过低,使用nvm升级
nvm install --lts
nvm use --lts

2. 网络问题

# 设置npm镜像
npm config set registry https://registry.npmmirror.com

# 或使用cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install

3. 权限问题

# macOS/Linux
sudo chown -R $(whoami) ~/.npm

# Windows (以管理员身份运行)
npm config set prefix %APPDATA%\npm

4. 端口占用

# 查看端口占用
netstat -ano | findstr :5173

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

# 或使用不同端口
npm run dev -- --port 3000

项目模板推荐

1. 官方模板

# 基础模板
npm create vue@latest

# TypeScript模板
npm create vite@latest my-project -- --template vue-ts

2. 社区模板

# Vue3 + TypeScript + Tailwind CSS
npm create vue@latest my-project
# 选择 TypeScript: Yes, Tailwind CSS: Yes

# Vue3 + Element Plus
git clone https://github.com/element-plus/element-plus-vite-starter.git

3. 企业级模板

# Vue3 Admin模板
git clone https://github.com/vbenjs/vue-vben-admin.git

# Naive UI Admin
git clone https://github.com/jekip/naive-ui-admin.git

总结

本课我们学习了Vue3开发环境的搭建:

  1. Node.js安装:多种安装方式和版本管理
  2. 项目创建:create-vue、Vue CLI、Vite
  3. 开发工具:VS Code、WebStorm、Chrome DevTools
  4. 项目配置:Vite、ESLint、Prettier
  5. 常见问题:网络、权限、端口等问题解决

下一课预告

在下一课中,我们将学习Vue3的基础语法,包括:

  • 模板语法和指令
  • 响应式数据绑定
  • 事件处理
  • 条件渲染和列表渲染

现在你已经有了完整的Vue3开发环境,让我们开始编写Vue3代码吧!


💡 小贴士:推荐使用Vite作为构建工具,它比Webpack更快,开发体验更好。同时建议配置好代码规范工具,养成良好的编码习惯。

Vue3 + TypeScript 企业级项目实战

课程推荐

Vue3 + TypeScript 企业级项目实战
Python 全栈开发工程师培训

热门课程

Python 全栈开发工程师培训

📚 文章对你有帮助?请关注我的公众号,万分感谢!

获取更多优质技术文章,第一时间掌握最新技术动态

关注公众号

关注公众号

第一时间获取最新技术文章

添加微信

添加微信

技术交流 · 问题答疑 · 学习指导

评论讨论

欢迎留下你的想法和建议