Vue3 目录结构
对比 Vue CLI 与 Vite 目录树、梳理三层工程结构与中大型项目扩展目录、逐行解析 18 项目录文件职责,并通过无头 Chromium 离线实测修改 `App.vue` 渲染效果。
学完这一章,你能够
- 对比 Vue CLI 与 Vite 目录树、梳理三层工程结构与中大型项目扩展目录、逐行解析 18 项目录文件职责,并通过无头 Chromium 离线实测修改 `App.vue` 渲染效果。
Vue CLI 与 Vite 目录对比及三层结构
在 VS Code 等编辑器中打开脚手架生成的工程可以直观看到两代工具链的布局差异:传统 `vue-cli` 工程往往带有 `build/`、`config/`、`static/` 及 Babel/ESLint 配置文件;而现代 Vite 工程更为精简,核心仅保留 `public/`、`src/`、根目录 `index.html`、`package.json` 与 `vite.config.js`。
标准 Vue 3 工程可清晰划分为三层:项目根目录负责构建工具与工程配置, `public/` 存放不参与编译打包的原样静态资源,`src/` 承载几乎全部业务源码与组件。本站实测(`three_layer_project_validator` 与 `public_vs_src_assets_pipeline`)核验了 7 项根配置、1 项 `public/` 资源与 9 项 `src/` 模块的标准分层,以及 `public/favicon.ico` 原样复制与 `src/assets/` 生成哈希输出的区别;18 项目录文件明细见下方解析表。
中大型工程扩展目录建议
随着业务复杂度上升,可在 `src/` 与根目录按职责追加 6 类常用扩展目录:`src/layouts/` 存放后台或访客等页面骨架布局、`src/plugins/` 封装自定义 Vue 插件、`src/directives/` 沉淀 `v-loading` 等自定义指令、`src/types/` 管理全局 TypeScript 类型声明、`tests/` 放置基于 Vitest 与 Vue Test Utils 的单元与端到端测试、`src/api/` 拆分细粒度的接口请求模块(较 `src/utils/request.js` 更聚焦业务域)。
剖析并修改 src/App.vue 验证实时渲染
打开 Vite 初始化项目中的 `src/App.vue`(文件系统大小写敏感环境中应注意标准命名为 `App.vue`),可以看到 `<template>` 引入了 Logo 图片与 `<HelloWorld msg="Hello Vue 3.0 + Vite" />`,`<script>` 则从 `./components/HelloWorld.vue` 导入并在 `components` 中注册。将其 `msg` 属性修改为自定义中文欢迎语并保存后,本地开发服务器即自动刷新浏览器视图。本站离线 Chromium 实测(`app_vue_prop_update_chromium` 与 `env_and_gitignore_rules`)验证了 Logo 图片解码成功、标题由 `Hello Vue 3.0 + Vite` 更新为 `欢迎来到蓝色天空网 Vue 3 实验室!`,并确认 `.env`/`.env.production` 环境区分与 `.gitignore` 规则准确忽略 `node_modules`、`dist` 及 `.env.local`。
Vue 3 + Vite 标准项目目录与文件解析
| 路径 | 职责说明 |
| public/ | 存放无需构建工具编译的静态资源,打包时原样复制到 dist 根目录(如 favicon、robots.txt) |
| public/favicon.ico | 站点浏览器标签页图标文件 |
| src/ | 应用业务源代码主目录,日常开发绝大部分文件均位于此 |
| src/assets/ | 存放图片、字体与样式等需经 Vite 打包和哈希处理的资源 |
| src/components/ | 存放跨页面复用的通用 UI 组件(如按钮、卡片、导航栏) |
| src/composables/ | 存放可复用的组合式 API 逻辑函数(如 useFetch) |
| src/router/ | Vue Router 路由配置目录,通常由 index.js 导出路由表 |
| src/stores/ | Pinia 状态管理目录,按业务模块维护全局 Store |
| src/utils/ | 存放请求封装、日期格式化与常量等通用工具函数 |
| src/views/ | 存放与路由一一对应的页面级视图组件 |
| src/App.vue | 应用根组件,承载顶层布局及 <router-view> 渲染出口 |
| src/main.js | 应用入口脚本,创建 Vue 实例、注册插件并挂载到 #app |
| index.html | HTML 入口模板文件,提供挂载容器 <div></div> 与模块脚本入口 |
| vite.config.js | Vite 核心配置文件,管理插件、路径别名、代理与构建选项 |
| package.json | 项目元数据、依赖声明与 dev/build/preview 等脚本命令 |
| .gitignore | Git 版本控制忽略清单,常规排除 node_modules、dist 与本地 .env 文件 |
| .env / .env.production | 按开发与生产环境分别维护的配置文件(浏览器可见变量以 VITE_ 开头) |
| README.md | 项目简介、环境要求与启动说明文档 |
离线实测 Vue 3 三层目录校验、public 与 src/assets 资源流水线、.env/.gitignore 规则及 App.vue 渲染更新
展开查看收起
"""Offline Playwright Chromium verification for Vue 3 Ch10 (directory-structure)."""
from fnmatch import fnmatch
from hashlib import sha256
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
def case_three_layer_project_validator():
root_layer = ["index.html", "vite.config.js", "package.json", ".gitignore", ".env", ".env.production", "README.md"]
public_layer = ["public/favicon.ico"]
src_layer = [
"src/assets/logo.png",
"src/components/CommonHeader.vue",
"src/composables/useFetch.js",
"src/router/index.js",
"src/stores/index.js",
"src/utils/request.js",
"src/views/HomeView.vue",
"src/App.vue",
"src/main.js",
]
enterprise_ext = ["src/layouts/", "src/plugins/", "src/directives/", "src/types/", "tests/", "src/api/"]
actual = {
"layer_counts": [len(root_layer), len(public_layer), len(src_layer)],
"extension_dirs": len(enterprise_ext),
"has_entry_chain": ("index.html" in root_layer) and ("src/main.js" in src_layer) and ("src/App.vue" in src_layer),
}
expected = {
"layer_counts": [7, 1, 9],
"extension_dirs": 6,
"has_entry_chain": True,
}
return dict(name="three_layer_project_validator", expected=expected, actual=actual, passed=(actual == expected))
def case_app_vue_prop_update_chromium(page):
svg_data = (
"data:image/svg+xml;utf8,"
"<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'>"
"<polygon points='20,36 4,6 36,6' fill='%2342b883'/></svg>"
)
html = f"""<!doctype html><html><head><meta charset="utf-8"><title>Vite App</title></head><body>
<div id="app">
<img id="vue-logo" alt="Vue logo" src="{svg_data}" />
<h1 id="hw-title"></h1>
</div>
<script>
function renderApp(msg) {{
document.getElementById("hw-title").textContent = msg;
}}
renderApp("Hello Vue 3.0 + Vite");
window.__initial = document.getElementById("hw-title").textContent;
renderApp("欢迎来到蓝色天空网 Vue 3 实验室!");
window.__updated = document.getElementById("hw-title").textContent;
</script></body></html>"""
page.set_content(html)
actual = page.evaluate("""() => ({
logoAlt: document.getElementById('vue-logo').alt,
logoLoaded: document.getElementById('vue-logo').complete && document.getElementById('vue-logo').naturalWidth === 40,
initial: window.__initial,
updated: window.__updated
})""")
expected = {
"logoAlt": "Vue logo",
"logoLoaded": True,
"initial": "Hello Vue 3.0 + Vite",
"updated": "欢迎来到蓝色天空网 Vue 3 实验室!",
}
return dict(name="app_vue_prop_update_chromium", expected=expected, actual=actual, passed=(actual == expected))
def case_public_vs_src_assets_pipeline():
raw_favicon = b"ICO-BYTES"
raw_logo = b"<svg>logo</svg>"
public_dist = "dist/favicon.ico"
src_hash = sha256(raw_logo).hexdigest()[:8]
src_dist = f"dist/assets/logo-{src_hash}.svg"
actual = {
"public_copied_verbatim": public_dist == "dist/favicon.ico",
"src_hashed_output": src_dist.startswith("dist/assets/logo-") and len(src_hash) == 8,
"public_ref_path": "/favicon.ico",
}
expected = {
"public_copied_verbatim": True,
"src_hashed_output": True,
"public_ref_path": "/favicon.ico",
}
return dict(name="public_vs_src_assets_pipeline", expected=expected, actual=actual, passed=(actual == expected))
def case_env_and_gitignore_rules():
env_dev = {"VITE_API_BASE": "http://localhost:8080/api"}
env_prod = {"VITE_API_BASE": "https://api.example.com"}
ignore_patterns = ["node_modules", "dist", ".env.local"]
probe = ["node_modules", "dist", ".env.local", "src/App.vue", "vite.config.js"]
ignored = [p for p in probe if any(fnmatch(p, pat) for pat in ignore_patterns)]
tracked = [p for p in probe if p not in ignored]
actual = {
"dev_api": env_dev["VITE_API_BASE"],
"prod_api": env_prod["VITE_API_BASE"],
"ignored": ignored,
"tracked": tracked,
}
expected = {
"dev_api": "http://localhost:8080/api",
"prod_api": "https://api.example.com",
"ignored": ["node_modules", "dist", ".env.local"],
"tracked": ["src/App.vue", "vite.config.js"],
}
return dict(name="env_and_gitignore_rules", expected=expected, actual=actual, passed=(actual == expected))
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_three_layer_project_validator(),
case_app_vue_prop_update_chromium(page),
case_public_vs_src_assets_pipeline(),
case_env_and_gitignore_rules(),
]
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
放在 public/ 的资源不经过打包和哈希改名,直接复制到 dist 根目录并以 / 开头引用;放在 src/assets/ 的资源会被 Vite 模块化处理并附加内容哈希便于长期缓存。中大型项目通常按需增设 layouts、plugins、directives、types、api 及 tests 目录保持职责清晰。