本章将详细介绍Vue.js开发环境的搭建,包括Node.js安装、项目创建工具、代码编辑器配置以及调试工具的使用。
2.1 Node.js环境安装
Node.js简介
Node.js是一个基于Chrome V8引擎的JavaScript运行时,是Vue.js开发的基础环境。
# 检查Node.js版本
node --version
# 输出示例:v18.17.0
# 检查npm版本
npm --version
# 输出示例:9.6.7
安装Node.js
方法1:官方安装包
# Windows
# 1. 访问 https://nodejs.org/
# 2. 下载LTS版本
# 3. 运行安装程序
# macOS
# 1. 访问 https://nodejs.org/
# 2. 下载LTS版本
# 3. 运行.pkg文件
# 或使用Homebrew
brew install node
# Linux (Ubuntu/Debian)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
# Linux (CentOS/RHEL)
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo yum install -y nodejs
方法2:版本管理工具
# 使用nvm (Node Version Manager)
# 安装nvm
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 list
# 切换版本
nvm use 18.17.0
# 使用fnm (Fast Node Manager)
# 安装fnm
curl -fsSL https://fnm.vercel.app/install | bash
# 安装Node.js
fnm install --lts
fnm use lts-latest
# 设置默认版本
fnm default lts-latest
npm配置优化
# 查看npm配置
npm config list
# 设置淘宝镜像源(中国用户推荐)
npm config set registry https://registry.npmmirror.com
# 验证镜像源
npm config get registry
# 设置npm缓存目录
npm config set cache "D:\npm-cache"
# 设置全局安装目录
npm config set prefix "D:\npm-global"
# 查看配置文件位置
npm config get userconfig
// .npmrc文件示例
registry=https://registry.npmmirror.com
cache=D:\npm-cache
prefix=D:\npm-global
save-exact=true
engine-strict=true
2.2 项目创建工具
Vite(推荐)
Vite是Vue.js官方推荐的现代构建工具,具有快速的冷启动和热更新特性。
# 创建Vue项目
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
Scaffolding project in ./my-vue-project...
Done.
# 进入项目目录
cd my-vue-project
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 预览生产构建
npm run preview
Vue CLI(传统工具)
# 全局安装Vue CLI
npm install -g @vue/cli
# 检查版本
vue --version
# 创建项目
vue create my-vue-cli-project
# 选择预设配置
? Please pick a preset:
Default ([Vue 3] babel, eslint)
Default ([Vue 2] babel, eslint)
❯ Manually select features
# 手动选择功能
? Check the features needed for your project:
◉ Babel
◯ TypeScript
◯ Progressive Web App (PWA) Support
◉ Router
◉ Vuex
◯ CSS Pre-processors
◉ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
# 进入项目
cd my-vue-cli-project
# 启动开发服务器
npm run serve
# 构建项目
npm run build
# 运行linter
npm run lint
项目结构对比
# Vite项目结构
my-vue-project/
├── public/
│ └── favicon.ico
├── src/
│ ├── assets/
│ ├── components/
│ ├── views/
│ ├── App.vue
│ └── main.js
├── index.html
├── package.json
├── vite.config.js
└── README.md
# Vue CLI项目结构
my-vue-cli-project/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── assets/
│ ├── components/
│ ├── views/
│ ├── App.vue
│ └── main.js
├── package.json
├── vue.config.js
└── README.md
2.3 代码编辑器配置
Visual Studio Code(推荐)
必装扩展
// .vscode/extensions.json
{
"recommendations": [
"Vue.volar", // Vue语言支持
"Vue.vscode-typescript-vue-plugin", // TypeScript支持
"bradlc.vscode-tailwindcss", // Tailwind CSS支持
"esbenp.prettier-vscode", // 代码格式化
"dbaeumer.vscode-eslint", // ESLint支持
"formulahendry.auto-rename-tag", // 自动重命名标签
"christian-kohler.path-intellisense", // 路径智能提示
"ms-vscode.vscode-json" // JSON支持
]
}
工作区配置
// .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.tabSize": 2,
"editor.insertSpaces": true,
"files.associations": {
"*.vue": "vue"
},
"emmet.includeLanguages": {
"vue-html": "html"
},
"typescript.preferences.quoteStyle": "single",
"javascript.preferences.quoteStyle": "single",
"vue.codeActions.enabled": true,
"vue.complete.casing.tags": "kebab",
"vue.complete.casing.props": "camel"
}
代码片段
// .vscode/vue.code-snippets
{
"Vue 3 Component": {
"prefix": "vue3",
"body": [
"<template>",
" <div class=\"$1\">",
" $2",
" </div>",
"</template>",
"",
"<script>",
"export default {",
" name: '$3',",
" data() {",
" return {",
" $4",
" }",
" },",
" methods: {",
" $5",
" }",
"}",
"</script>",
"",
"<style scoped>",
"$6",
"</style>"
],
"description": "Vue 3 component template"
},
"Vue 3 Composition API": {
"prefix": "vue3-composition",
"body": [
"<template>",
" <div>",
" $1",
" </div>",
"</template>",
"",
"<script setup>",
"import { ref, reactive, computed, onMounted } from 'vue'",
"",
"// 响应式数据",
"const $2 = ref('')",
"const state = reactive({",
" $3",
"})",
"",
"// 计算属性",
"const $4 = computed(() => {",
" $5",
"})",
"",
"// 生命周期",
"onMounted(() => {",
" $6",
"})",
"",
"// 方法",
"const $7 = () => {",
" $8",
"}",
"</script>",
"",
"<style scoped>",
"$9",
"</style>"
],
"description": "Vue 3 Composition API template"
}
}
WebStorm配置
// webstorm.config.js
module.exports = {
// Vue文件模板
fileTemplates: {
'Vue Component': {
extension: 'vue',
template: `
<template>
<div class="#[[$COMPONENT_NAME$]]#">
<!-- 组件内容 -->
</div>
</template>
<script>
export default {
name: '#[[$COMPONENT_NAME$]]#',
data() {
return {
// 数据属性
}
},
methods: {
// 方法
}
}
</script>
<style scoped>
.#[[$COMPONENT_NAME$]]# {
/* 样式 */
}
</style>
`
}
},
// 代码风格
codeStyle: {
indentSize: 2,
tabSize: 2,
useTab: false,
wrapOnTyping: true
}
}
2.4 浏览器开发工具
Vue DevTools
# 安装Vue DevTools浏览器扩展
# Chrome: https://chrome.google.com/webstore/detail/vuejs-devtools/
# Firefox: https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/
# Edge: https://microsoftedge.microsoft.com/addons/detail/vuejs-devtools/
// 在开发环境中启用Vue DevTools
// main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 开发环境配置
if (process.env.NODE_ENV === 'development') {
app.config.devtools = true
app.config.debug = true
app.config.silent = false
}
app.mount('#app')
调试技巧
// 1. 使用debugger语句
export default {
methods: {
handleClick() {
debugger // 浏览器会在此处暂停
console.log('按钮被点击')
}
}
}
// 2. 使用console.log调试
export default {
data() {
return {
message: 'Hello Vue'
}
},
watch: {
message(newVal, oldVal) {
console.log('message changed:', { newVal, oldVal })
}
}
}
// 3. 使用Vue DevTools
export default {
name: 'MyComponent',
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
// 在Vue DevTools中可以实时查看count的变化
}
}
}
性能分析
// 性能监控
export default {
name: 'PerformanceComponent',
mounted() {
// 记录组件挂载时间
console.time('component-mount')
this.initializeComponent()
console.timeEnd('component-mount')
},
methods: {
initializeComponent() {
// 组件初始化逻辑
},
// 性能敏感的方法
expensiveOperation() {
console.time('expensive-operation')
// 执行耗时操作
for (let i = 0; i < 1000000; i++) {
// 计算密集型任务
}
console.timeEnd('expensive-operation')
}
}
}
2.5 包管理工具
npm vs yarn vs pnpm
# npm(Node.js默认包管理器)
npm install vue
npm install --save-dev @vitejs/plugin-vue
npm run dev
npm run build
# yarn(Facebook开发的包管理器)
yarn add vue
yarn add --dev @vitejs/plugin-vue
yarn dev
yarn build
# pnpm(性能优化的包管理器)
pnpm add vue
pnpm add -D @vitejs/plugin-vue
pnpm dev
pnpm build
依赖管理最佳实践
// package.json
{
"name": "my-vue-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore",
"format": "prettier --write src/",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.3.4",
"vue-router": "^4.2.4",
"pinia": "^2.1.6"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.3.4",
"vite": "^4.4.9",
"eslint": "^8.49.0",
"prettier": "^3.0.3",
"@vue/eslint-config-prettier": "^8.0.0"
},
"engines": {
"node": ">=16.0.0",
"npm": ">=8.0.0"
}
}
# 锁定依赖版本
npm ci # 使用package-lock.json安装确切版本
yarn install --frozen-lockfile # 使用yarn.lock安装确切版本
pnpm install --frozen-lockfile # 使用pnpm-lock.yaml安装确切版本
# 更新依赖
npm update
yarn upgrade
pnpm update
# 检查过时的依赖
npm outdated
yarn outdated
pnpm outdated
# 审计安全漏洞
npm audit
yarn audit
pnpm audit
2.6 构建工具配置
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'),
'@components': resolve(__dirname, 'src/components'),
'@views': resolve(__dirname, 'src/views'),
'@assets': resolve(__dirname, 'src/assets'),
'@utils': resolve(__dirname, 'src/utils')
}
},
// 开发服务器配置
server: {
port: 3000,
open: true,
cors: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
// 构建配置
build: {
outDir: 'dist',
sourcemap: true,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
},
rollupOptions: {
output: {
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js',
assetFileNames: '[ext]/[name]-[hash].[ext]'
}
}
},
// CSS配置
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
},
// 环境变量
define: {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false
}
})
环境变量配置
# .env
VITE_APP_TITLE=My Vue App
VITE_APP_VERSION=1.0.0
# .env.development
VITE_API_BASE_URL=http://localhost:8080/api
VITE_APP_DEBUG=true
# .env.production
VITE_API_BASE_URL=https://api.example.com
VITE_APP_DEBUG=false
# .env.local (不会被git追踪)
VITE_SECRET_KEY=your-secret-key
// 在Vue组件中使用环境变量
export default {
data() {
return {
appTitle: import.meta.env.VITE_APP_TITLE,
apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
isDebug: import.meta.env.VITE_APP_DEBUG === 'true'
}
},
mounted() {
console.log('App Title:', this.appTitle)
console.log('API Base URL:', this.apiBaseUrl)
console.log('Debug Mode:', this.isDebug)
}
}
2.7 代码质量工具
ESLint配置
// .eslintrc.cjs
module.exports = {
root: true,
env: {
node: true,
browser: true,
es2022: true
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/eslint-config-prettier'
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'vue/multi-word-component-names': 'off',
'vue/no-unused-vars': 'error',
'vue/no-unused-components': 'warn',
'prefer-const': 'error',
'no-var': 'error'
},
overrides: [
{
files: ['*.vue'],
rules: {
'vue/component-name-in-template-casing': ['error', 'PascalCase']
}
}
]
}
Prettier配置
// .prettierrc
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"printWidth": 80,
"bracketSpacing": true,
"arrowParens": "avoid",
"vueIndentScriptAndStyle": true,
"endOfLine": "lf"
}
# .prettierignore
dist
node_modules
*.md
package-lock.json
yarn.lock
pnpm-lock.yaml
Git Hooks
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
"lint-staged": {
"*.{js,vue}": [
"eslint --fix",
"prettier --write",
"git add"
],
"*.{css,scss,vue}": [
"prettier --write",
"git add"
]
}
}
# 安装相关依赖
npm install --save-dev husky lint-staged @commitlint/cli @commitlint/config-conventional
# 初始化husky
npx husky install
# 添加pre-commit钩子
npx husky add .husky/pre-commit "npx lint-staged"
# 添加commit-msg钩子
npx husky add .husky/commit-msg "npx commitlint --edit $1"
本章小结
本章我们学习了:
- Node.js环境:安装、配置和版本管理
- 项目创建工具:Vite和Vue CLI的使用
- 代码编辑器:VS Code和WebStorm的配置
- 浏览器工具:Vue DevTools的使用和调试技巧
- 包管理工具:npm、yarn、pnpm的对比和使用
- 构建工具:Vite配置和环境变量管理
- 代码质量:ESLint、Prettier和Git Hooks配置
下一章预告
下一章我们将学习Vue.js的基本语法,包括: - 模板语法和插值 - 指令系统 - 事件处理 - 表单输入绑定
练习题
基础练习
环境搭建:
- 安装Node.js和npm
- 使用Vite创建一个Vue项目
- 配置VS Code开发环境
项目配置:
- 配置ESLint和Prettier
- 设置路径别名
- 配置环境变量
进阶练习
工具使用:
- 安装Vue DevTools
- 练习使用浏览器调试工具
- 配置Git Hooks
性能优化:
- 配置Vite构建优化
- 设置代码分割
- 配置CDN资源
提示:良好的开发环境是高效开发的基础,建议花时间配置好各种工具和插件。