使用 Vue 脚手架创建项目的完整指南
Vue 提供了多种脚手架工具来快速创建项目,本文将详细介绍最常用的两种方式:Vue CLI 和 Vite,并比较它们的优缺点。
一、Vue CLI 创建项目
Vue CLI 是 Vue 官方提供的标准脚手架工具,适合构建中大型项目。
1. 安装 Vue CLI
首先确保已安装 Node.js (推荐 14.18+ 或 16+ 版本),然后全局安装 Vue CLI:
bash
npm install -g @vue/cli
# 或
yarn global add @vue/cli
验证安装是否成功:
bash
vue --version
2. 创建项目
bash
vue create my-project
3. 项目配置选项
运行命令后,你会看到交互式配置界面:
-
选择预设:
Default ([Vue 2] babel, eslint)
- Vue 2 默认配置Default (Vue 3) ([Vue 3] babel, eslint)
- Vue 3 默认配置Manually select features
- 手动选择功能
-
手动选择功能(选择后):
text? 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
-
选择 Vue 版本:
text? Choose a version of Vue.js that you want to start the project with 3.x 2.x
-
选择路由模式:
plaintext? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n)
-
选择 CSS 预处理器:
pl? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass) Sass/SCSS (with node-sass) Less Stylus
-
选择代码规范:
lua? Pick a linter / formatter config: ESLint with error prevention only ESLint + Airbnb config ESLint + Standard config ESLint + Prettier
-
选择何时进行代码检查:
csharp? Pick additional lint features: ◉ Lint on save ◯ Lint and fix on commit
-
选择配置文件存放位置:
lua? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files In package.json
-
是否保存为预设:
kotlin? Save this as a preset for future projects? (y/N)
4. 项目结构
创建完成后的项目结构:
arduino
my-project/
├── node_modules/
├── public/
│ ├── favicon.ico
│ └── index.html
├── src/
│ ├── assets/
│ ├── components/
│ ├── router/
│ ├── store/
│ ├── views/
│ ├── App.vue
│ └── main.js
├── .gitignore
├── babel.config.js
├── package.json
└── README.md
5. 运行项目
bash
cd my-project
npm run serve
项目将运行在 http://localhost:8080/
二、Vite 创建 Vue 项目
Vite 是新一代前端构建工具,启动速度极快,适合现代 Vue 3 项目。
1. 创建项目
bash
npm create vite@latest my-vite-project -- --template vue
# 或
yarn create vite my-vite-project --template vue
命令分解:
bash
npm create vite@latest my-vite-project -- --template vue
-
npm create
-
这是 npm 6+ 版本提供的快捷命令,等同于:
bashnpx create-vite@latest
-
它会临时下载并执行
create-vite
这个脚手架工具。
-
-
vite@latest
- 指定使用最新版本的 Vite 脚手架工具。
@latest
确保总是获取最新的稳定版。
-
my-vite-project
- 这是你要创建的项目文件夹名称(可自定义)。
-
-- --template vue
- 第一个
--
表示将后续参数传递给create-vite
命令。 --template vue
指定使用 Vue 模板(Vite 支持多种框架模板)。
- 第一个
其他可用模板:
Vite 支持多种模板,可通过替换 vue
选择:
bash
npm create vite@latest my-app -- --template [template-name]
模板名 | 说明 |
---|---|
vue |
Vue 3 项目 |
vue-ts |
Vue 3 + TypeScript |
react |
React 项目 |
react-ts |
React + TypeScript |
vanilla |
纯 JavaScript 项目 |
vanilla-ts |
纯 TypeScript 项目 |
常见问题:
Q1: 可以创建 Vue 2 项目吗? A: Vite 官方模板仅支持 Vue 3。如需 Vue 2,需手动配置或使用 vue-cli
。
Q2: 如何指定 Vite 版本? A: 替换 @latest
,例如 vite@3.2.0
。
Q3: 为什么用 --
分隔参数? A: 这是 npm 的语法规则,--
后的参数会传递给被调用的脚本(即 create-vite
)。
2. 选择模板
Vite 提供多种模板选择:
plaintext
? Select a template:
vanilla
vue
react
preact
lit
svelte
选择 vue
或 vue-ts
(TypeScript 版本)
3. 项目结构
Vite 创建的项目结构更简洁:
plaintext
my-vite-project/
├── node_modules/
├── public/
├── src/
│ ├── assets/
│ ├── components/
│ ├── App.vue
│ └── main.js
├── .gitignore
├── index.html
├── package.json
├── vite.config.js
└── README.md
4. 运行项目
bash
cd my-vite-project
npm install
npm run dev
项目将运行在 http://localhost:5173/
三、Vue CLI 与 Vite 对比
特性 | Vue CLI | Vite |
---|---|---|
构建工具 | Webpack | Rollup (生产) / ESBuild (开发) |
启动速度 | 较慢 (20-30s) | 极快 (0.5-2s) |
HMR 速度 | 1-3s | 50-100ms |
配置复杂度 | 复杂 | 简单 |
插件生态 | 丰富 | 正在增长 |
Vue 版本 | 支持 Vue 2 & 3 | 主要 Vue 3 |
适合场景 | 企业级大型项目 | 现代轻量项目 |
四、添加常用功能
1. 添加 Vue Router
Vue CLI 项目(已自动安装)
如果创建时选择了 Router,则已配置完成。
Vite 项目手动安装:
bash
npm install vue-router@4
创建 src/router/index.js
:
js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
export default router
在 main.js
中使用:
js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
2. 添加状态管理
Vue CLI 项目(已自动安装 Vuex)
如果创建时选择了 Vuex,则已配置完成。
Vite 项目推荐使用 Pinia:
bash
npm install pinia
创建 store src/stores/counter.js
:
js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
},
getters: {
doubleCount: (state) => state.count * 2
}
})
在 main.js
中使用:
js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
3. 添加 CSS 预处理器
Sass/SCSS
bash
npm install sass -D
使用示例:
html
<style lang="scss">
$primary-color: #42b983;
.header {
color: $primary-color;
}
</style>
Less
bash
npm install less -D
使用示例:
html
<style lang="less">
@primary-color: #42b983;
.header {
color: @primary-color;
}
</style>
五、项目配置
Vue CLI 配置
配置文件:vue.config.js
js
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/my-project/' : '/',
devServer: {
port: 8081,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
},
css: {
loaderOptions: {
sass: {
additionalData: `@import "@/styles/variables.scss";`
}
}
}
}
Vite 配置
配置文件:vite.config.js
php
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
server: {
port: 8081,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
}
})
六、构建与部署
构建生产版本
Vue CLI
bash
npm run build
生成 dist/
目录
Vite
bash
npm run build
生成 dist/
目录
本地预览生产版本
Vue CLI
bash
npm run serve -- --mode production
Vite
bash
npm run preview
部署到服务器
- 将
dist
目录上传到服务器 - 配置 Web 服务器(以 Nginx 为例):
nginx
ini
server {
listen 80;
server_name yourdomain.com;
location / {
root /path/to/your/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
}
七、常见问题解决
1. 端口冲突
修改开发服务器端口:
Vue CLI
vue.config.js
js
module.exports = {
devServer: {
port: 8081
}
}
Vite
vite.config.js
js
export default defineConfig({
server: {
port: 8081
}
})
2. 路径别名不生效
确保正确配置别名:
Vue CLI
jsconfig.json
js
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
Vite
vite.config.js
js
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})
3. 浏览器兼容性问题
Vue CLI
安装 @vue/cli-plugin-babel/preset
并配置 babel.config.js
Vite
安装 @vitejs/plugin-legacy
bash
npm install @vitejs/plugin-legacy -D
配置 vite.config.js
:
js
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
plugins: [
legacy({
targets: ['defaults', 'not IE 11']
})
]
})
八、项目示例:Todo App
Vue CLI 版本
bash
vue create todo-app
# 选择默认 Vue 3 预设
Vite 版本
bash
npm create vite@latest todo-app -- --template vue
核心代码 src/components/TodoList.vue
js
<template>
<div class="todo-app">
<h1>Todo List</h1>
<input
v-model="newTodo"
@keyup.enter="addTodo"
placeholder="Add a new task"
>
<ul>
<li v-for="(todo, index) in todos" :key="todo.id">
<input
type="checkbox"
v-model="todo.completed"
>
<span :class="{ completed: todo.completed }">
{{ todo.text }}
</span>
<button @click="removeTodo(index)">×</button>
</li>
</ul>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const newTodo = ref('')
const todos = ref([
{ id: 1, text: 'Learn Vue', completed: false },
{ id: 2, text: 'Build an app', completed: false }
])
function addTodo() {
if (newTodo.value.trim() === '') return
todos.value.push({
id: Date.now(),
text: newTodo.value,
completed: false
})
newTodo.value = ''
}
function removeTodo(index) {
todos.value.splice(index, 1)
}
return {
newTodo,
todos,
addTodo,
removeTodo
}
}
}
</script>
<style>
.todo-app {
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.completed {
text-decoration: line-through;
color: #888;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
ul {
list-style: none;
padding: 0;
}
li {
display: flex;
align-items: center;
padding: 8px 0;
}
button {
margin-left: auto;
background: #ff6b6b;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}
</style>
九、总结
通过 Vue CLI 或 Vite 创建 Vue 项目都非常简单:
- Vue CLI :
- 适合需要完整 Webpack 配置的大型项目
- 提供更多内置功能和插件
- 支持 Vue 2 和 Vue 3
- Vite :
- 超快的启动和热更新速度
- 更简单的配置
- 专注于现代浏览器
- 主要支持 Vue 3
根据项目需求选择合适的工具:
- 企业级复杂项目 → Vue CLI
- 现代轻量级应用 → Vite
无论选择哪种方式,Vue 的生态系统都能为你提供强大的开发体验和丰富的功能支持。