用 create-vue 创建 Vue 3 项目

摘要

  • 用官方脚手架 create-vue 生成带 TypeScript、vue-router、Pinia 的 Vue 3 项目,逐步说明交互选项,并解释生成后每个文件和目录的作用
  • 本文按 Node v24.14.0、create-vue@3.24.0。生成结果对应 Vue 3.5.x、Vue Router 5.x、Pinia 4.x、Vite 8.x、TypeScript 6.x
  • 官方文档:create-vue、Quick Start、Vite、Vue Router、Pinia。npm 基础见 npm使用手册

前置条件

脚手架要求 Node ^22.18.0 || >=24.12.0。本机用 v24.14.0,满足要求。

1
2
node -v
npm -v

工作目录可以任意。下面在 vue3_study 下创建,项目名是 vue3-demo。

启动脚手架

1
2
3
4
5
# 进入学习目录
cd /Users/hanqf/vue_workspaces/vue3_study

# 拉取并运行官方 create-vue
npm create vue@latest

npm create vue@latest 等价于 npx create-vue@latest。第一次会下载脚手架包,随后进入交互问答。

交互选项

Project name

1
2
◇  Project name (target directory):
│ vue3-demo

这里填的是目标目录名,也是 package.json 里的 name。生成路径是当前目录下的 vue3-demo/。

Use TypeScript

1
2
◇  Use TypeScript?
│ Yes

选 Yes。脚本入口是 src/main.ts,组件用 <script setup lang="ts">,类型检查走 vue-tsc。

Select features

1
2
3
4
5
6
7
8
◆  Select features to include in your project:
│ ◻ JSX Support
│ ◻ Router (SPA development)
│ ◻ Pinia (state management)
│ ◻ Vitest (unit testing)
│ ◻ End-to-End Testing
│ ◻ Linter (error prevention)
│ ◻ Prettier (code formatting)

用空格勾选,回车确认。学习 SPA 路由和状态管理时,只勾 Router 和 Pinia。

选项 怎么选 说明
JSX Support 不勾 组件用 .vue 单文件即可,不必引入 JSX
Router (SPA development) 勾 生成 src/router,依赖 vue-router
Pinia (state management) 勾 生成 src/stores,依赖 pinia
Vitest 不勾 单元测试后补,先减依赖
End-to-End Testing 不勾 端到端测试同理后补
Linter 不勾 不生成 ESLint 配置
Prettier 不勾 不生成 Prettier 配置

确认后应显示:

1
2
◇  Select features to include in your project:
│ Router (SPA development), Pinia (state management)

Element Plus、axios 不在脚手架里,项目生成后再单独安装。

Select experimental features

1
2
3
4
◆  Select experimental features to include in your project:
│ ◻ Replace Prettier with Oxfmt
│ ◻ Vue 3.6 (Release Candidate)
│ ◻ Replace TypeScript with typescript-native-bridge (tsgo)

三项都不要勾,直接回车。结果应是 none。

选项 为什么不勾
Replace Prettier with Oxfmt 上一步没选 Prettier,勾了也没有对应配置
Vue 3.6 (Release Candidate) 仍是候选版;当前后台用稳定版 Vue 3.5
typescript-native-bridge (tsgo) 试验阶段;学习项目用普通 TypeScript

Skip all example code

1
2
◆  Skip all example code and start with a blank Vue project?
│ ○ Yes / ● No

停在 No,直接回车。

选 No 会留下官方示例:欢迎页组件、Home / About 路由页、Pinia 计数仓库。勾了 Router 和 Pinia 之后,这些示例就是它们的最小接法。选 Yes 得到几乎空白的工程,路由和状态管理只有空壳,对照 src/router、src/stores 反而不方便。

完整交互结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
◇  Project name (target directory):
│ vue3-demo
│
◇ Use TypeScript?
│ Yes
│
◇ Select features to include in your project:
│ Router (SPA development), Pinia (state management)
│
◇ Select experimental features to include in your project:
│ none
│
◇ Skip all example code and start with a blank Vue project?
│ No

Scaffolding project in .../vue3-demo...
│
└ Done. Now run:

cd vue3-demo
npm install
npm run dev

安装依赖并启动

1
2
3
cd /Users/hanqf/vue_workspaces/vue3_study/vue3-demo
npm install
npm run dev

本机实际输出示例:

1
2
3
4
5
6
7
8
9
10
> vue3-demo@0.0.0 dev
> vite

VITE v8.3.8 ready in 2059 ms

➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ Vue DevTools: Open http://localhost:5173/__devtools__/ as a separate window
➜ Vue DevTools: Press Option(⌥)+Shift(⇧)+D in App to toggle the Vue DevTools
➜ press h + enter to show help
行 含义
Local: http://localhost:5173/ 本机浏览器打开这个地址看示例首页
Network: use --host to expose 默认只监听本机。需要手机或其它机器访问时,改用 npm run dev -- --host
Vue DevTools: .../__devtools__/ 脚手架默认加了 vite-plugin-vue-devtools,可单独开这个地址看组件树
Option+Shift+D 在页面里切换内嵌 DevTools 面板
h + enter 终端里显示 Vite 快捷键帮助

在开发服务器仍在跑的终端里按 h 再回车,会列出:

1
2
3
4
5
6
Shortcuts
press r + enter to restart the server
press u + enter to show server url
press o + enter to open in browser
press c + enter to clear console
press q + enter to quit
快捷键 作用
r + 回车 重启开发服务器
u + 回车 再打印一次 Local / Network 地址
o + 回车 用系统默认浏览器打开 Local 地址
c + 回车 清空终端输出
q + 回车 退出开发服务器(和 Ctrl+C 同类)

有 vite-plugin-vue-devtools 时,不必再装浏览器里的 Vue DevTools 扩展。插件只在 npm run dev 时生效,打开 __devtools__ 或按 ⌥⇧D 就能看组件树、Pinia、路由。浏览器扩展是另一套入口,适合没有这个插件的项目;两边功能重叠,学习项目用脚手架自带的即可。

看到 ready 且 Local 能打开,开发环境就算起来了。改 src 下的文件会热更新,不必重启命令。

脚手架可选地提示初始化 Git:

1
git init && git add -A && git commit -m "initial commit"

是否执行由你决定,不影响后续开发。

生成结果里的版本

本次生成的 package.json 依赖大致如下;npm install 后本机锁到的 Vite 运行时是 v8.3.8:

包 版本范围 角色
vue ^3.5.42 框架
vue-router ^5.3.1 路由
pinia ^4.0.3 状态管理
vite ^8.2.2 开发服务器与打包
typescript ~6.0.0 类型系统
vue-tsc ^3.3.11 对 .vue 做类型检查
@vitejs/plugin-vue ^6.0.8 Vite 的 Vue 插件
vite-plugin-vue-devtools ^8.2.1 开发时 Vue DevTools,不影响生产构建
npm-run-all2 ^9.0.3 build 时并行跑类型检查和打包

engines.node 写的是 ^22.18.0 || >=24.12.0。

package.json 里的常用脚本:

脚本 作用
npm run dev 启动 Vite 开发服务器,热更新
npm run build 先 vue-tsc --build 类型检查,再 vite build 产出静态资源
npm run build-only 只打包,不做类型检查
npm run type-check 只做类型检查
npm run preview 预览 build 产物

目录总览

生成后(安装依赖前)大致是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
vue3-demo
├── env.d.ts
├── index.html
├── package.json
├── public
│ └── favicon.ico
├── README.md
├── src
│ ├── App.vue
│ ├── assets
│ │ ├── base.css
│ │ ├── logo.svg
│ │ └── main.css
│ ├── components
│ │ ├── HelloWorld.vue
│ │ ├── icons
│ │ │ ├── IconCommunity.vue
│ │ │ ├── IconDocumentation.vue
│ │ │ ├── IconEcosystem.vue
│ │ │ ├── IconSupport.vue
│ │ │ └── IconTooling.vue
│ │ ├── TheWelcome.vue
│ │ └── WelcomeItem.vue
│ ├── main.ts
│ ├── router
│ │ └── index.ts
│ ├── stores
│ │ └── counter.ts
│ └── views
│ ├── AboutView.vue
│ └── HomeView.vue
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts

npm install 之后还会出现 node_modules/、package-lock.json。开发时 Vite 可能再生成 node_modules/.vite、node_modules/.tmp 等缓存目录,不必提交到版本库。

根目录文件

package.json

项目元数据、脚本、依赖声明。private: true 表示不打算发布到 npm。type: "module" 表示按 ES Module 解析 .js / 配置文件。

index.html

单页应用的 HTML 壳。页面里只有一个挂载点 #app,以及指向入口脚本的模块标签:

1
2
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>

Vite 以项目根目录的 index.html 为入口,开发时由开发服务器提供,构建时再把脚本、样式打进产物。

vite.config.ts

Vite 配置。本次模板默认做了三件事:

  • 启用 @vitejs/plugin-vue,让 Vite 能编译 .vue

  • 启用 vite-plugin-vue-devtools,开发时挂 Vue DevTools

  • 配置路径别名 @ 指向 src/,所以可以写 import xxx from '@/components/...'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})

env.d.ts

1
/// <reference types="vite/client" />

给 TypeScript 引入 Vite 客户端类型,例如 import.meta.env、以及把 .vue、静态资源当作模块导入时的类型声明。没有这份引用,编辑器会对这些导入报类型错误。

tsconfig.json / tsconfig.app.json / tsconfig.node.json

采用 project references 拆成两套编译上下文:

文件 作用
tsconfig.json 根配置,只引用另外两个,本身不含源文件
tsconfig.app.json 浏览器端应用代码:src/**/*、.vue、env.d.ts。继承 @vue/tsconfig,并配置 @/* 路径映射
tsconfig.node.json 跑在 Node 里的配置文件:vite.config.* 等。继承 @tsconfig/node24

vue-tsc --build 会按这两套分别做增量类型检查,增量信息写在 node_modules/.tmp/ 下的 .tsbuildinfo。

README.md

脚手架自带的英文说明:推荐的 VS Code + Vue (Official) 扩展、浏览器 DevTools、以及 npm install / npm run dev / npm run build 命令。可按团队习惯改写或删掉。

public/favicon.ico

不经 Vite 模块图处理、原样拷到产物根目录的静态资源。站点图标、robots.txt 这类固定路径文件放这里。需要被 JS 导入、参与哈希命名的图片放 src/assets。

src 目录

src/main.ts

应用入口。创建根实例,挂上 Pinia 和 Router,再挂载到 #app:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import './assets/main.css'

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')

顺序有含义:先 use 插件,再 mount。全局样式也在这里引入一次。

src/App.vue

根组件。模板里放顶栏(Logo、HelloWorld、导航),以及 <RouterView /> 作为路由出口。当前路由匹配到哪个页面,就渲染到这个出口里。

<RouterLink> 做客户端跳转,不会整页刷新。导航高亮用的是 router-link-exact-active 一类 class。

src/router/index.ts

路由表。createWebHistory 使用 HTML5 History 模式,URL 形如 /about,没有 #。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/about',
name: 'about',
// 访问时再加载,单独打成一个 chunk
component: () => import('../views/AboutView.vue'),
},
],
})

export default router

HomeView 是同步导入,首屏就会打进主包。AboutView 是动态 import(),第一次进 /about 才下载对应 chunk。

createWebHistory 和服务端

开发时不用额外配:npm run dev 的 Vite 已经会把找不到的路径回退到 index.html,直接刷新 /about 没问题。

生产部署必须让 Nginx(或其它静态服务器)做同样的回退。原因在于:createWebHistory 把路由写进真实路径(/about),但磁盘上并没有名为 about 的文件。npm run build 之后,dist/ 里通常只有:

  • index.html:整站唯一的 HTML 入口

  • assets/*.js、assets/*.css:带哈希的打包文件

  • favicon.ico 等 public/ 原样拷出的文件

前端路由只存在于浏览器里的 JS。两种访问方式差别很大:

操作 谁处理 /about 没配回退时
已打开站点后,点 <RouterLink to="/about"> 浏览器里的 vue-router,多数情况下不会向服务器要 /about 这个 HTML 看起来正常
地址栏直接打开,或在 /about 上按刷新 浏览器向 Nginx 请求路径 /about Nginx 按文件找,找不到 → 404,Vue 根本没机会启动

所以不是「Nginx 要认识 Vue 路由」,而是:凡是磁盘上没有的路径,都先把 index.html 交出去,让 main.ts → vue-router 根据当前 URL 再渲染对应页面。官方说明与其它服务器写法见 Different History modes。

Nginx 用 try_files 表达这条规则:

1
2
3
location / {
try_files $uri $uri/ /index.html;
}

按顺序尝试三次:

参数 含义 例子
$uri 有没有与请求路径同名的文件 /assets/index-AbCd.js → 直接返回该文件
$uri/ 有没有同名目录 少见;有目录时再按 index 处理
/index.html 前两步都没有 → 内部改去返回根上的 index.html 请求 /about、/user/1 时走这里

没有这行时,刷新 /about 得到的是 Nginx 的 404 页。有了这行,刷新 /about 拿到的仍是 SPA 入口,页面里的 Router 再显示 About。真实存在的 /assets/... 仍由前两步原样提供,不会被错误地换成 index.html。

生产环境通常还会给带哈希的静态资源加缓存。npm run build 后,Vite 默认把 js / css 打到 dist/assets/,文件名里带内容哈希(例如 index-AbCdEf.js)。内容变了文件名就变,浏览器只会再请求新 URL,旧文件名的长缓存不会把新版本卡住。真正必须控制的是 index.html:路径固定、发布后要立刻更新,不能长缓存,否则用户会一直拿到旧的资源清单。

哈希已经保证「同一 URL 内容不变」,再长也不会因为发版而脏读;设成 7d、30d 就可以了。

若要加,示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 80;
server_name example.com;
root /var/www/vue3-demo/dist;
index index.html;

# 带哈希的构建产物:一条 Cache-Control 写全;时长按习惯改 max-age
location /assets/ {
add_header Cache-Control "public, max-age=2592000, immutable" always;
}

# 其它路径:先找文件,没有则回退 SPA
location / {
try_files $uri $uri/ /index.html;
}
}

add_header Cache-Control "public, immutable" always; 拆开看:

片段 含义
add_header Nginx 往响应里加一个 HTTP 头
Cache-Control 告诉浏览器 / CDN 怎么缓存这份响应
public 浏览器和共享缓存(CDN、代理)都可以存
immutable 新鲜期内不必发条件请求做 304 校验;支持的浏览器即使用户刷新也不重新确认。适用于版本化 URL(文件名含内容哈希),见 RFC 8246
always Nginx 特有。默认 add_header 只加在部分成功状态码上;加上 always 后,4xx / 5xx 也会带上这个头

上面示例里的 max-age=2592000 是 30 天(秒)。只写 public, immutable、不写 max-age / Expires 时,新鲜期不明确,浏览器行为不可靠,所以时长要写进同一条 Cache-Control。若只要过期时间、不要 public / immutable,可以单独用 expires 30d;,由 Nginx 生成带 max-age 的 Cache-Control。

不要在同一 location 里同时写 expires 30d; 和 add_header Cache-Control "..."。expires 会生成 Cache-Control: max-age=...,再 add_header 同名时不会覆盖,而是再增加一个独立的 Cache-Control 头。HTTP 允许存在多个同名头,但部分 CDN 或中间件可能只读第一个,导致 public / immutable 或 max-age 丢失。需要这些指令时,写成上面这一条即可。

immutable 只适合内容哈希资源。没有哈希的文件不要加。

index.html 走后面的 location /,不要给它加长缓存。public/ 里原样拷出的文件(如 favicon.ico)没有内容哈希,若也要缓存,单独写更短的过期时间即可。

回退后,服务器侧几乎不会再对未知路径返回 404。前端要自己加一条兜底路由,例如 path: '/:pathMatch(.*)*',用来显示 Not Found 页。

若部署在子目录(例如 https://example.com/app/),vite.config.ts 的 base 和 createWebHistory(...) 的 base 要一致;模板里写的 import.meta.env.BASE_URL 就是接这个值。

不想改服务器时可用 createWebHashHistory(),URL 变成 /#/about。# 后面的部分不会发给服务器,因此不需要回退配置,但地址栏带 #,对 SEO 也不友好。学习项目、能控制 Nginx 时,继续用 createWebHistory 即可。

src/stores/counter.ts

Pinia 示例仓库,用 Composition API 写法(setup store):

1
2
3
4
5
6
7
8
9
10
11
12
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}

return { count, doubleCount, increment }
})

组件里 const counter = useCounterStore() 即可读写。新业务状态可以继续在 src/stores/ 下按模块加文件。

src/views/

按路由划分的页面级组件:

文件 路由 作用
HomeView.vue / 首页,引入 TheWelcome
AboutView.vue /about 关于页,示例懒加载页面

页面负责布局和组合子组件;可复用的块放 components/。

src/components/

文件 / 目录 作用
HelloWorld.vue 接收 msg prop,显示欢迎标题
TheWelcome.vue 首页主体,拼装若干 WelcomeItem
WelcomeItem.vue 欢迎区列表项的布局壳
icons/*.vue 欢迎区用到的 SVG 图标组件

这些都是示例 UI。正式业务可以逐步替换或删除,不影响 Router / Pinia 的接法。

src/assets/

文件 作用
base.css 基础变量与重置样式(来自 Vue 主题色板)
main.css 引入 base.css,并写 #app 等全局布局
logo.svg 顶栏 Vue Logo,经 Vite 处理,可在组件里用 @/assets/logo.svg 引用

启动后怎么对照代码

浏览器打开首页后:

  1. index.html 提供 #app

  2. main.ts 创建应用,注册 Pinia、Router,挂载 App.vue

  3. App.vue 渲染顶栏,<RouterView /> 根据当前路径渲染 HomeView 或 AboutView

  4. 点导航到 About,触发 AboutView 的懒加载 chunk

  5. 需要全局状态时,对照 stores/counter.ts 的写法新建 store

确认环境正常的最短路径:npm run dev 能打开首页,导航到 About 无报错,npm run type-check 通过。

下一步常见安装

脚手架没有内置 UI 库和 HTTP 客户端。需要时在项目目录单独安装,例如:

1
2
3
4
5
# UI 组件库(按需再配自动导入)
npm install element-plus

# HTTP 客户端
npm install axios

安装后在 main.ts 或具体模块里引入;具体配置另文再写。