文章目录
1. Vue CLI简介
1.1 什么是Vue CLI?
Vue CLI(Command Line Interface)是Vue.js官方提供的标准化命令行工具,用于快速搭建Vue.js项目。它提供了一整套完整的开发环境配置,包括项目结构、构建工具、开发服务器、测试框架等,让开发者可以专注于业务逻辑的开发。
1.2 Vue CLI的主要特点
1.2.1 标准化项目结构
- 统一的目录结构
- 规范的文件命名
- 清晰的代码组织
1.2.2 开箱即用的配置
- Webpack构建配置
- Babel转译配置
- ESLint代码检查
- 热重载开发服务器
1.2.3 丰富的插件生态
- 官方插件支持
- 社区插件扩展
- 可插拔架构设计
1.2.4 多种项目模板
- 基础模板
- TypeScript模板
- PWA模板
- 多页面应用模板
1.3 Vue CLI与其他工具的对比
特性 | Vue CLI | Create React App | Angular CLI |
---|---|---|---|
学习曲线 | 中等 | 简单 | 复杂 |
配置灵活性 | 高 | 中等 | 高 |
插件生态 | 丰富 | 中等 | 丰富 |
TypeScript支持 | 内置 | 内置 | 原生 |
构建工具 | Webpack | Webpack | Webpack |
2. 环境准备
2.1 Node.js安装
2.1.1 下载Node.js
步骤1:访问官网
- 打开浏览器,访问 https://nodejs.org/
- 选择LTS版本(长期支持版本,推荐)
- 根据操作系统选择对应的安装包
Windows系统:
- 下载
.msi
文件 - 双击安装,按照向导完成安装
- 安装过程中会自动配置环境变量
macOS系统:
- 下载
.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
# CentOS/RHEL
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo yum install -y nodejs
2.1.2 验证安装
打开命令行工具(Terminal、命令提示符或PowerShell),运行以下命令:
# 检查Node.js版本
node --version
# 或
node -v
# 检查npm版本
npm --version
# 或
npm -v
正确的输出示例:
$ node -v
v18.17.0
$ npm -v
9.6.7
注意: Vue CLI 4+ 需要Node.js 8.9以上版本(推荐12.0以上)
2.1.3 npm配置优化
# 查看npm配置
npm config list
# 设置npm镜像源(可选,提高下载速度)
npm config set registry https://registry.npmmirror.com
# 验证镜像源设置
npm config get registry
# 设置缓存目录(可选)
npm config set cache "D:\nodejs\npm-cache"
# 设置全局模块安装目录(可选)
npm config set prefix "D:\nodejs\npm-global"
2.2 包管理器选择
2.2.1 npm(默认)
# npm是Node.js自带的包管理器
# 无需额外安装
npm --version
2.2.2 yarn(推荐)
# 安装yarn
npm install -g yarn
# 验证安装
yarn --version
# 设置yarn镜像源
yarn config set registry https://registry.npmmirror.com
2.2.3 pnpm(高效选择)
# 安装pnpm
npm install -g pnpm
# 验证安装
pnpm --version
# 设置pnpm镜像源
pnpm config set registry https://registry.npmmirror.com
2.3 开发工具选择
2.3.1 Visual Studio Code(推荐)
安装步骤:
- 访问 https://code.visualstudio.com/
- 下载对应操作系统版本
- 安装并启动
推荐插件:
必装插件:
- Vetur(Vue 2支持)
- Vue Language Features (Volar)(Vue 3支持)
- ES7+ React/Redux/React-Native snippets
- Auto Rename Tag
- Bracket Pair Colorizer
- Prettier - Code formatter
- ESLint
可选插件:
- GitLens
- Live Server
- Vue VSCode Snippets
- Path Intellisense
- Material Theme
2.3.2 WebStorm
- 功能强大的IDE
- 内置Vue支持
- 收费软件,学生可免费使用
2.3.3 Sublime Text
- 轻量级编辑器
- 需要安装Vue语法高亮插件
3. Vue CLI安装
3.1 全局安装Vue CLI
3.1.1 使用npm安装
# 安装最新版本Vue CLI
npm install -g @vue/cli
# 查看安装版本
vue --version
# 或
vue -V
3.1.2 使用yarn安装
# 使用yarn全局安装
yarn global add @vue/cli
# 查看版本
vue --version
3.1.3 使用pnpm安装
# 使用pnpm全局安装
pnpm add -g @vue/cli
# 查看版本
vue --version
3.1.4 验证安装成功
$ vue --version
@vue/cli 5.0.8
# 查看Vue CLI帮助信息
$ vue --help
Usage: vue <command> [options]
Options:
-V, --version output the version number
-h, --help display help for command
Commands:
create [options] <app-name> create a new project powered by vue-cli-service
add [options] <plugin> [pluginOptions] add a plugin to an already created project
invoke [options] <plugin> [pluginOptions] invoke a plugin in an already created project
inspect [options] [paths...] inspect the webpack config in a project with vue-cli-service
serve [options] [entry] serve a .js or .vue file in development mode with zero config
build [options] [entry] build a .js or .vue file in production mode with zero config
ui start and open the vue-cli ui
init [options] <template> <app-name> generate a project from a remote template (legacy API, requires @vue/cli-init)
config [options] [value] inspect and modify the config
outdated [options] (experimental) check for outdated vue cli service / plugins
upgrade [options] [plugin-name] (experimental) upgrade vue cli service / plugins
migrate [options] [plugin-name] (experimental) run migrator for an already-installed cli plugin
info print debugging information about the local environment
Run vue <command> --help for detailed usage of given command.
3.2 更新Vue CLI
# 查看当前版本
vue --version
# 更新到最新版本
npm update -g @vue/cli
# 或使用yarn
yarn global upgrade @vue/cli
# 或使用pnpm
pnpm update -g @vue/cli
# 如果遇到权限问题(Windows)
npm install -g @vue/cli --force
# 如果遇到权限问题(macOS/Linux)
sudo npm install -g @vue/cli
3.3 卸载Vue CLI
# 使用npm卸载
npm uninstall -g @vue/cli
# 使用yarn卸载
yarn global remove @vue/cli
# 使用pnpm卸载
pnpm remove -g @vue/cli
4. 创建第一个Vue项目
4.1 使用vue create命令
4.1.1 基本创建命令
# 创建新项目
vue create my-first-vue-project
# 进入项目目录
cd my-first-vue-project
# 启动开发服务器
npm run serve
4.1.2 项目名称规范
有效的项目名称:
vue create my-project ✅ 推荐:小写字母+连字符
vue create myproject ✅ 可用:小写字母
vue create my_project ✅ 可用:下划线
vue create hello-world ✅ 推荐:描述性名称
无效的项目名称:
vue create MyProject ❌ 不能包含大写字母
vue create my project ❌ 不能包含空格
vue create 123project ❌ 不能以数字开头
vue create vue ❌ 不能使用保留关键字
4.2 选择预设配置
4.2.1 创建过程详解
步骤1:运行创建命令
$ vue create my-first-project
步骤2:选择预设
Vue CLI v5.0.8
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 3] babel, eslint)
Default ([Vue 2] babel, eslint)
Manually select features
预设选项说明:
-
Default ([Vue 3] babel, eslint)
- Vue 3版本
- Babel转译器
- ESLint代码检查
- 最简配置,适合快速开始
-
Default ([Vue 2] babel, eslint)
- Vue 2版本
- Babel转译器
- ESLint代码检查
- 稳定版本,兼容性好
-
Manually select features
- 手动选择功能
- 自定义配置
- 适合有特定需求的项目
4.2.2 手动选择功能详解
选择"Manually select features"后会出现功能选择界面:
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Babel
◯ TypeScript
◯ Progressive Web App (PWA) Support
◯ Router
◯ Vuex
◯ CSS Pre-processors
◯ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
功能说明:
-
Babel ✅ 推荐选择
- JavaScript转译器
- 支持ES6+语法
- 浏览器兼容性
-
TypeScript 可选
- 静态类型检查
- 更好的IDE支持
- 大型项目推荐
-
Progressive Web App (PWA) Support 可选
- 渐进式Web应用
- 离线功能
- 原生应用体验
-
Router ✅ 推荐选择
- Vue路由管理
- 单页面应用必需
- 页面导航功能
-
Vuex 可选
- 状态管理
- 复杂应用推荐
- 组件间数据共享
-
CSS Pre-processors ✅ 推荐选择
- CSS预处理器
- Sass、Less、Stylus支持
- 提高CSS开发效率
-
Linter / Formatter ✅ 推荐选择
- 代码风格检查
- 自动格式化
- 团队协作必需
-
Unit Testing 可选
- 单元测试
- Jest或Mocha
- 保证代码质量
-
E2E Testing 可选
- 端到端测试
- Cypress或Nightwatch
- 功能测试
4.3 详细配置选择
4.3.1 Vue版本选择
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
❯ 3.x
2.x
版本对比:
特性 | Vue 2.x | Vue 3.x |
---|---|---|
性能 | 良好 | 更优 |
TypeScript支持 | 一般 | 优秀 |
Composition API | 插件支持 | 原生支持 |
生态系统 | 成熟 | 快速发展 |
学习成本 | 低 | 中等 |
推荐选择:
- 新项目:选择Vue 3.x
- 维护旧项目:选择Vue 2.x
- 学习阶段:建议从Vue 3.x开始
4.3.2 路由配置
? Use history mode for router? (requires proper server setup for index fallback in production) (Y/n)
路由模式对比:
-
History模式(推荐)
URL示例:https://example.com/user/profile
- URL更美观
- SEO友好
- 需要服务器配置
-
Hash模式
URL示例:https://example.com/#/user/profile
- 无需服务器配置
- URL包含#号
- 兼容性更好
4.3.3 CSS预处理器选择
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
❯ Sass/SCSS (with dart-sass)
Less
Stylus
预处理器对比:
-
Sass/SCSS ✅ 推荐
- 功能最强大
- 社区最活跃
- 支持嵌套、变量、混合等
-
Less
- 学习曲线平缓
- Bootstrap使用
- 功能相对简单
-
Stylus
- 语法最灵活
- 可选分号和大括号
- 社区相对较小
4.3.4 代码检查工具选择
? Pick a linter / formatter config: (Use arrow keys)
❯ ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
ESLint + Prettier
配置说明:
-
ESLint with error prevention only
- 基础错误检查
- 规则较少
- 适合初学者
-
ESLint + Airbnb config ✅ 推荐
- Airbnb编码规范
- 规则严格
- 业界标准
-
ESLint + Standard config
- JavaScript Standard规范
- 无分号风格
- 简洁规则
-
ESLint + Prettier ✅ 强烈推荐
- 代码格式化
- 自动修复
- 团队协作最佳
4.3.5 代码检查时机
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Lint on save
◯ Lint and fix on commit
选项说明:
- Lint on save: 保存时检查,实时反馈
- Lint and fix on commit: 提交时检查,确保代码质量
4.3.6 测试框架选择
单元测试:
? Pick a unit testing solution: (Use arrow keys)
❯ Jest
Mocha + Chai
E2E测试:
? Pick an E2E testing solution: (Use arrow keys)
❯ Cypress (Chrome only)
Nightwatch (WebDriver-based)
WebdriverIO (WebDriver/DevTools based)
4.3.7 配置文件位置
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files
In package.json
选择建议:
- In dedicated config files: 配置清晰,推荐
- In package.json: 文件集中,简洁
4.3.8 保存预设
? Save this as a preset for future projects? (y/N)
如果选择保存,系统会要求输入预设名称:
? Save preset as: my-preset
5. 项目结构详解
5.1 标准项目目录结构
创建完成后的项目结构如下:
my-first-vue-project/
├── public/ # 静态资源目录
│ ├── favicon.ico # 网站图标
│ └── index.html # 主HTML模板
├── src/ # 源码目录
│ ├── assets/ # 资源文件
│ ├── components/ # 组件目录
│ ├── router/ # 路由配置
│ ├── store/ # 状态管理
│ ├── views/ # 页面组件
│ ├── App.vue # 根组件
│ └── main.js # 入口文件
├── tests/ # 测试文件
├── .gitignore # Git忽略文件
├── babel.config.js # Babel配置
├── package.json # 项目依赖配置
├── README.md # 项目说明文档
└── vue.config.js # Vue CLI配置(可选)
5.2 重要文件详细说明
5.2.1 package.json
{
"name": "my-first-vue-project",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve", // 开发服务器
"build": "vue-cli-service build", // 生产构建
"lint": "vue-cli-service lint" // 代码检查
},
"dependencies": {
"core-js": "^3.8.3", // 核心polyfill
"vue": "^3.2.13", // Vue框架
"vue-router": "^4.0.3" // 路由管理
},
"devDependencies": {
"@babel/core": "^7.12.16", // Babel核心
"@babel/eslint-parser": "^7.12.16", // Babel ESLint解析器
"@vue/cli-plugin-babel": "~5.0.0", // Babel插件
"@vue/cli-plugin-eslint": "~5.0.0", // ESLint插件
"@vue/cli-service": "~5.0.0", // CLI服务
"eslint": "^7.32.0", // ESLint
"eslint-plugin-vue": "^8.0.3" // Vue ESLint插件
}
}
5.2.2 main.js(入口文件)
// Vue 3版本
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 创建Vue应用实例
const app = createApp(App)
// 使用插件
app.use(store) // 状态管理
app.use(router) // 路由
// 挂载到DOM
app.mount('#app')
5.2.3 App.vue(根组件)
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>
5.2.4 index.html(主模板)
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
5.3 目录结构最佳实践
5.3.1 推荐的目录组织
src/
├── api/ # API接口
│ ├── index.js # API统一导出
│ ├── user.js # 用户相关API
│ └── product.js # 产品相关API
├── assets/ # 静态资源
│ ├── images/ # 图片资源
│ ├── styles/ # 样式文件
│ │ ├── base.css # 基础样式
│ │ ├── variables.css # CSS变量
│ │ └── common.css # 通用样式
│ └── fonts/ # 字体文件
├── components/ # 通用组件
│ ├── common/ # 公共组件
│ │ ├── Header.vue
│ │ ├── Footer.vue
│ │ └── Loading.vue
│ └── business/ # 业务组件
│ ├── UserCard.vue
│ └── ProductList.vue
├── views/ # 页面组件
│ ├── Home/
│ │ ├── index.vue
│ │ └── components/ # 页面专用组件
│ └── About/
│ └── index.vue
├── router/ # 路由配置
│ ├── index.js # 主路由
│ └── modules/ # 路由模块
├── store/ # 状态管理
│ ├── index.js # Store入口
│ └── modules/ # Store模块
├── utils/ # 工具函数
│ ├── request.js # HTTP请求封装
│ ├── storage.js # 本地存储
│ └── date.js # 日期处理
├── mixins/ # 混入
├── directives/ # 自定义指令
└── plugins/ # 插件
5.3.2 命名规范
文件命名:
✅ 推荐:
- PascalCase: UserProfile.vue, ProductList.vue
- kebab-case: user-profile.vue, product-list.vue
❌ 避免:
- camelCase: userProfile.vue
- snake_case: user_profile.vue
组件命名:
<!-- ✅ 推荐:多词名称 -->
<template>
<user-profile></user-profile>
<product-card></product-card>
</template>
<!-- ❌ 避免:单词名称 -->
<template>
<user></user>
<card></card>
</template>
6. 开发服务器详解
6.1 启动开发服务器
6.1.1 基本启动命令
# 使用npm
npm run serve
# 使用yarn
yarn serve
# 使用pnpm
pnpm run serve
6.1.2 启动过程详解
$ npm run serve
> my-first-vue-project@0.1.0 serve
> vue-cli-service serve
INFO Starting development server...
DONE Compiled successfully in 2857ms
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.1.100:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
输出信息说明:
- Local: 本地访问地址
- Network: 网络访问地址(其他设备可访问)
- 开发构建未优化: 开发模式包含调试信息
6.1.3 自定义启动配置
在package.json中自定义脚本:
{
"scripts": {
"serve": "vue-cli-service serve",
"dev": "vue-cli-service serve --mode development",
"serve:prod": "vue-cli-service serve --mode production",
"serve:8081": "vue-cli-service serve --port 8081",
"serve:host": "vue-cli-service serve --host 0.0.0.0"
}
}
命令行参数:
# 指定端口
npm run serve -- --port 3000
# 指定主机
npm run serve -- --host 0.0.0.0
# 自动打开浏览器
npm run serve -- --open
# HTTPS模式
npm run serve -- --https
# 组合使用
npm run serve -- --port 3000 --open --https
6.2 热重载功能
6.2.1 什么是热重载?
热重载(Hot Module Replacement, HMR)是开发服务器的核心功能,它允许在不刷新整个页面的情况下更新模块。
热重载的优势:
- 保持应用状态
- 快速反映代码更改
- 提高开发效率
- 无需手动刷新页面
6.2.2 热重载示例
修改组件文件:
<!-- HelloWorld.vue -->
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<!-- 修改这里的内容,保存后立即看到效果 -->
<p>欢迎使用Vue.js开发!</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
修改样式文件:
<style scoped>
.hello {
color: #42b983; /* 修改颜色,保存后立即生效 */
}
</style>
6.2.3 热重载配置
在vue.config.js中配置:
module.exports = {
devServer: {
hot: true, // 启用热重载
hotOnly: true, // 只使用HMR,不刷新页面
overlay: { // 错误覆盖层
warnings: false,
errors: true
}
}
}
6.3 开发服务器配置
6.3.1 创建vue.config.js
在项目根目录创建vue.config.js
文件:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// 基本配置
publicPath: '/', // 部署路径
outputDir: 'dist', // 构建输出目录
assetsDir: 'static', // 静态资源目录
indexPath: 'index.html', // index.html路径
filenameHashing: true, // 文件名哈希
// 开发服务器配置
devServer: {
port: 8080, // 端口号
host: 'localhost', // 主机名
https: false, // 是否启用HTTPS
open: true, // 自动打开浏览器
hot: true, // 热重载
// 代理配置
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
// 覆盖配置
overlay: {
warnings: false,
errors: true
}
},
// 其他配置
lintOnSave: true, // 保存时进行lint检查
transpileDependencies: [], // 需要转译的依赖
productionSourceMap: false, // 生产环境source map
// 插件配置
pluginOptions: {
// 插件特定配置
}
})
6.3.2 代理配置详解
单个代理:
module.exports = {
devServer: {
proxy: 'http://localhost:3000'
}
}
多个代理:
module.exports = {
devServer: {
proxy: {
// 代理API请求
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': '/api/v1'
}
},
// 代理WebSocket
'/ws': {
target: 'ws://localhost:3000',
ws: true,
changeOrigin: true
},
// 条件代理
'/upload': {
target: 'http://localhost:3001',
changeOrigin: true,
bypass: function (req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
return '/index.html'
}
}
}
}
}
}
6.3.3 环境变量配置
创建环境文件:
.env
(所有环境)
VUE_APP_API_BASE_URL=http://localhost:3000
VUE_APP_APP_NAME=我的Vue应用
.env.development
(开发环境)
NODE_ENV=development
VUE_APP_API_BASE_URL=http://localhost:3000
VUE_APP_DEBUG=true
.env.production
(生产环境)
NODE_ENV=production
VUE_APP_API_BASE_URL=https://api.example.com
VUE_APP_DEBUG=false
在代码中使用:
// main.js
console.log('API Base URL:', process.env.VUE_APP_API_BASE_URL)
console.log('App Name:', process.env.VUE_APP_APP_NAME)
console.log('Debug Mode:', process.env.VUE_APP_DEBUG)
// 在组件中使用
export default {
data() {
return {
apiUrl: process.env.VUE_APP_API_BASE_URL
}
}
}
7. 构建和部署
7.1 构建项目
7.1.1 生产构建
# 构建生产版本
npm run build
# 使用yarn
yarn build
# 使用pnpm
pnpm run build
7.1.2 构建过程详解
$ npm run build
> my-first-vue-project@0.1.0 build
> vue-cli-service build
⠙ Building for production...
DONE Compiled successfully in 5034ms
File Size Gzipped
dist/js/chunk-vendors.a7c9d6cb.js 69.83 kb 25.26 kb
dist/js/app.fb81c4d7.js 4.62 kb 1.67 kb
dist/css/app.33c3fb28.css 0.33 kb 0.23 kb
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
7.1.3 构建输出分析
dist目录结构:
dist/
├── css/
│ └── app.33c3fb28.css # 样式文件
├── js/
│ ├── app.fb81c4d7.js # 应用代码
│ └── chunk-vendors.a7c9d6cb.js # 第三方库
├── favicon.ico # 图标
└── index.html # 主页面
文件说明:
- app.js: 应用主要代码
- chunk-vendors.js: 第三方依赖库
- app.css: 应用样式
- 文件名哈希: 用于缓存控制
7.1.4 自定义构建配置
// vue.config.js
module.exports = {
// 构建目录
outputDir: 'build',
// 静态资源目录
assetsDir: 'assets',
// 文件名哈希
filenameHashing: true,
// 生产环境source map
productionSourceMap: false,
// 配置webpack
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial'
}
}
}
}
},
// 链式操作webpack配置
chainWebpack: config => {
// 移除prefetch插件
config.plugins.delete('prefetch')
// 配置别名
config.resolve.alias
.set('@', resolve('src'))
.set('components', resolve('src/components'))
}
}
7.2 预览构建结果
7.2.1 本地预览
# 安装http-server
npm install -g http-server
# 进入构建目录
cd dist
# 启动静态服务器
http-server -p 8080
# 或使用Python(如果已安装)
python -m http.server 8080
# 使用Node.js serve包
npx serve -s dist -l 8080
7.2.2 使用Vue CLI预览
# 安装预览插件
vue add @vue/cli-plugin-pwa
# 构建并预览
npm run build
npx serve -s dist
7.3 部署到服务器
7.3.1 静态文件服务器部署
Nginx配置示例:
server {
listen 80;
server_name example.com;
location / {
root /var/www/vue-app/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
}
}
Apache配置示例:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/vue-app/dist
<Directory "/var/www/vue-app/dist">
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</Directory>
</VirtualHost>
7.3.2 GitHub Pages部署
1. 安装gh-pages包:
npm install --save-dev gh-pages
2. 配置package.json:
{
"scripts": {
"deploy": "gh-pages -d dist"
},
"homepage": "https://yourusername.github.io/your-repo-name"
}
3. 配置vue.config.js:
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/your-repo-name/'
: '/'
}
4. 部署命令:
npm run build
npm run deploy
7.3.3 Netlify部署
1. 在项目根目录创建netlify.toml
:
[build]
publish = "dist"
command = "npm run build"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
2. 连接GitHub仓库到Netlify
3. 配置构建设置
4. 自动部署
7.3.4 Vercel部署
1. 安装Vercel CLI:
npm install -g vercel
2. 在项目根目录创建vercel.json
:
{
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}
3. 部署:
vercel --prod
8. 常见问题与解决方案
8.1 安装相关问题
8.1.1 npm安装失败
问题描述:
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
解决方案:
# 方案1:使用sudo(Linux/macOS)
sudo npm install -g @vue/cli
# 方案2:更改npm默认目录
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
# 方案3:使用nvm管理Node.js版本
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
nvm install node
nvm use node
8.1.2 网络连接问题
问题描述:
npm ERR! network timeout
npm ERR! network This is a problem related to network connectivity.
解决方案:
# 方案1:更换npm镜像源
npm config set registry https://registry.npmmirror.com
# 方案2:使用cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install -g @vue/cli
# 方案3:配置代理(如果使用代理)
npm config set proxy http://proxy-server:port
npm config set https-proxy http://proxy-server:port
8.1.3 版本兼容性问题
问题描述:
vue : 无法将"vue"项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
解决方案:
# 检查Node.js版本
node --version
# 检查Vue CLI是否正确安装
npm list -g @vue/cli
# 重新安装Vue CLI
npm uninstall -g @vue/cli
npm install -g @vue/cli@latest
# Windows PowerShell执行策略问题
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
8.2 开发环境问题
8.2.1 端口被占用
问题描述:
Port 8080 is already in use.
解决方案:
# 方案1:使用其他端口
npm run serve -- --port 3000
# 方案2:查找并终止占用进程
# Windows
netstat -ano | findstr :8080
taskkill /PID <PID> /F
# macOS/Linux
lsof -ti:8080
kill -9 <PID>
# 方案3:配置默认端口
# 在vue.config.js中配置
module.exports = {
devServer: {
port: 3000
}
}
8.2.2 热重载失效
问题描述:
修改代码后页面不自动更新
解决方案:
// vue.config.js
module.exports = {
devServer: {
hot: true,
watchOptions: {
poll: 1000, // 轮询监听文件变化
aggregateTimeout: 500,
ignored: /node_modules/
}
}
}
8.2.3 内存不足
问题描述:
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
解决方案:
# 方案1:增加Node.js内存限制
node --max-old-space-size=4096 node_modules/@vue/cli-service/bin/vue-cli-service.js serve
# 方案2:在package.json中配置
{
"scripts": {
"serve": "node --max-old-space-size=4096 node_modules/@vue/cli-service/bin/vue-cli-service.js serve"
}
}
# 方案3:设置环境变量
export NODE_OPTIONS="--max-old-space-size=4096"
8.3 构建部署问题
8.3.1 路径问题
问题描述:
部署后资源文件404
解决方案:
// vue.config.js
module.exports = {
// 根据部署环境配置路径
publicPath: process.env.NODE_ENV === 'production'
? '/my-app/' // 部署在子目录
: '/', // 开发环境根目录
// 或使用相对路径
publicPath: './'
}
8.3.2 History路由404
问题描述:
刷新页面后出现404错误
解决方案:
# Nginx配置
location / {
try_files $uri $uri/ /index.html;
}
# Apache配置
RewriteEngine On
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
8.3.3 跨域问题
问题描述:
API请求跨域错误
解决方案:
// 开发环境代理配置
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
// 生产环境CORS配置(后端)
app.use(cors({
origin: 'https://your-domain.com',
credentials: true
}))
9. 项目优化建议
9.1 性能优化
9.1.1 代码分割
// 路由懒加载
const Home = () => import('@/views/Home.vue')
const About = () => import('@/views/About.vue')
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
9.1.2 资源优化
// vue.config.js
module.exports = {
chainWebpack: config => {
// 图片压缩
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
mozjpeg: { progressive: true, quality: 65 },
optipng: { enabled: false },
pngquant: { quality: [0.65, 0.90], speed: 4 },
gifsicle: { interlaced: false }
})
}
}
9.1.3 包大小分析
# 安装分析工具
npm install --save-dev webpack-bundle-analyzer
# 分析构建结果
npx vue-cli-service build --report
9.2 开发体验优化
9.2.1 别名配置
// vue.config.js
const path = require('path')
module.exports = {
chainWebpack: config => {
config.resolve.alias
.set('@', path.resolve(__dirname, 'src'))
.set('components', path.resolve(__dirname, 'src/components'))
.set('views', path.resolve(__dirname, 'src/views'))
.set('assets', path.resolve(__dirname, 'src/assets'))
}
}
9.2.2 自动导入
// vite.config.js (如果使用Vite)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
vue(),
AutoImport({
imports: ['vue', 'vue-router'],
dts: true
})
]
})
9.3 代码质量
9.3.1 ESLint配置
// .eslintrc.js
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
'@vue/standard'
],
parserOptions: {
parser: '@babel/eslint-parser',
requireConfigFile: false
},
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'
}
}
9.3.2 Prettier配置
// .prettierrc
{
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"tabWidth": 2,
"useTabs": false
}
10. 学习资源推荐
10.1 官方文档
- Vue.js官方文档: https://cn.vuejs.org/
- Vue CLI官方文档: https://cli.vuejs.org/zh/
- Vue Router文档: https://router.vuejs.org/zh/
- Vuex文档: https://vuex.vuejs.org/zh/
10.2 学习教程
- Vue.js入门教程: 从基础语法开始学习
- 组件化开发: 掌握组件设计和通信
- 状态管理: 学习Vuex或Pinia使用
- 路由管理: 掌握单页面应用开发
10.3 实践项目
- TodoList应用: 练习基础操作
- 博客系统: 综合运用各种特性
- 电商网站: 复杂业务场景实践
- 管理后台: 企业级应用开发
10.4 社区资源
- GitHub: 查看开源项目代码
- 掘金: 技术文章和经验分享
- Vue.js社区: 官方社区讨论
- Stack Overflow: 问题解答平台
11. 总结
通过本指南,您已经掌握了Vue CLI项目创建的全过程,包括:
- 环境准备: Node.js安装和配置
- 工具安装: Vue CLI安装和验证
- 项目创建: 使用命令行创建项目
- 配置选择: 根据需求选择合适配置
- 项目结构: 理解标准项目目录结构
- 开发服务器: 启动和配置开发环境
- 构建部署: 项目构建和部署上线
- 问题解决: 常见问题的解决方案
- 优化建议: 性能和开发体验优化
Vue CLI为Vue.js开发提供了完整的工具链支持,让开发者可以专注于业务逻辑而不是环境配置。建议在实际项目中多加练习,逐步掌握各种配置选项和最佳实践。
记住,学习Vue.js是一个渐进的过程,从简单的组件开始,逐步学习路由、状态管理、构建优化等高级特性,最终能够独立开发完整的Web应用。