环境搭建
核对使用 Vite 创建 TaskHub Vue 3 工程、清理默认模板、配置 @ 路径别名及接入 Tailwind CSS v4 Vite 插件与 @theme 主题变量的完整流程。
学完这一章,你能够
- 核对使用 Vite 创建 TaskHub Vue 3 工程、清理默认模板、配置 @ 路径别名及接入 Tailwind CSS v4 Vite 插件与 @theme 主题变量的完整流程。
使用 Vite 初始化 TaskHub 工程
TaskHub 采用 Vite 构建 Vue 3 项目(选用 `<script setup>` 写法),终端支持按包管理器选用 `npm create vite@latest task-hub -- --template vue`、`yarn create vite task-hub --template vue` 或速度更快的 `pnpm create vite task-hub -- --template vue`。
项目初始化并启动开发服务器后,终端会输出 Vite 就绪耗时与本地访问地址(默认 `http://localhost:5173/`),打开浏览器即可看到包含计数按钮的 Vue 3 默认欢迎页。
项目目录结构与默认代码清理
执行 `cd task-hub` 进入工程根目录后,可使用 `code .` 在 VS Code 中打开目录,查看 `index.html`、`package.json`、`vite.config.js`、`public/` 与 `src/` 等标准结构;日常开发先执行 `npm install` 安装依赖,再运行 `npm run dev` 启动本地热更新服务。本站核对 `cli_commands_inventory` 确认三类脚手架命令均指向 `--template vue` 与 5 个核心入口文件。
清理脚手架示例文件时,需删除 `src/components/HelloWorld.vue`、清空 `src/style.css`,并将 `src/App.vue` 精简为仅保留 `<script setup>` 与 `<h1>TaskHub</h1>` 标题的最小根组件。本站 Chromium 实测挂载清理后的根组件确认:`document.title` 为 `task-hub`,`#app h1` 文本为 `TaskHub`,且页面不再包含默认示例的 `count is 0` 计数器。
集成 Tailwind CSS v4 与 @ 路径别名
安装原子化样式依赖需执行 `npm install tailwindcss @tailwindcss/vite`,随后在 `vite.config.js` 的 `plugins` 中同时注册 `vue()` 与 `tailwindcss()`,并在 `resolve.alias` 中将 `@` 映射到 `./src`。Tailwind v4 直接作为 Vite 插件运行,会自动扫描工程内 `.vue` 文件按需生成工具类。本站配置解析实测确认:`@/components/TaskItem.vue` 解析为 `src/components/TaskItem.vue`,`@/stores/taskStore.js` 解析为 `src/stores/taskStore.js`。
Tailwind v4 采用 CSS 优先配置模式:在 `src/style.css` 顶部写入 `@import "tailwindcss";`,直接在 `@theme` 块声明 `--color-brand: #3b82f6` 与 `--radius-xl: 1rem` 主题变量,并在 `@layer base` 中为 `body` 设置浅灰背景、深色文字与抗锯齿样式。本站 Chromium 计算样式实测核对:`--color-brand` 为 `#3b82f6`、`--radius-xl` 为 `1rem`,`body` 背景为 `rgb(248, 250, 252)`、文字为 `rgb(15, 23, 42)`,引用主题变量的徽章背景为 `rgb(59, 130, 246)`、圆角为 `16px`。
验证清理后的 TaskHub 根组件挂载、@ 别名规则与 Tailwind v4 CSS 变量样式
展开查看收起
"""Offline Playwright Chromium lab for Vue3 Ch32: TaskHub Vite + Tailwind v4 setup."""
import json
from playwright.sync_api import sync_playwright
HTML = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>task-hub</title>
<style>
@layer base, utilities;
:root {
--color-brand: #3b82f6;
--radius-xl: 1rem;
}
@layer base {
body {
background-color: #f8fafc;
color: #0f172a;
-webkit-font-smoothing: antialiased;
margin: 0;
font-family: system-ui, sans-serif;
}
}
@layer utilities {
.bg-brand { background-color: var(--color-brand); }
.rounded-xl-token { border-radius: var(--radius-xl); }
}
</style>
</head>
<body>
<div id="app"></div>
<script>
// Simulate cleaned src/App.vue mount into #app (HelloWorld.vue removed)
const appEl = document.getElementById('app');
appEl.innerHTML = '<div><h1>TaskHub</h1><button id="brand-chip" class="bg-brand rounded-xl-token">Ready</button></div>';
// Simulate vite.config.js plugin & @ alias resolution
const viteConfig = {
plugins: ['vue', '@tailwindcss/vite'],
resolve: { alias: { '@': './src' } },
server: { port: 5173 }
};
window.__resolveAlias = function(specifier) {
for (const [k, target] of Object.entries(viteConfig.resolve.alias)) {
if (specifier.startsWith(k + '/')) {
return target.replace(/^\.\//, '') + specifier.slice(k.length);
}
}
return specifier;
};
window.__viteMeta = {
plugins: viteConfig.plugins,
port: viteConfig.server.port,
cliTemplates: {
npm: 'npm create vite@latest task-hub -- --template vue',
yarn: 'yarn create vite task-hub --template vue',
pnpm: 'pnpm create vite task-hub -- --template vue'
},
entryFiles: ['index.html', 'src/main.js', 'src/App.vue', 'vite.config.js', 'src/style.css']
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML, wait_until="domcontentloaded")
# Case 1: Cleaned App.vue mount & starter template removal
act1 = page.evaluate("""() => ({
docTitle: document.title,
h1Text: document.querySelector('#app h1')?.textContent,
hasHelloWorldCounter: document.body.textContent.includes('count is 0')
})""")
exp1 = {"docTitle": "task-hub", "h1Text": "TaskHub", "hasHelloWorldCounter": False}
cases.append({"name": "scaffold_and_entry_mount", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: Vite plugins & @ path alias resolution
act2 = page.evaluate("""() => ({
plugins: window.__viteMeta.plugins,
resolvedComponent: window.__resolveAlias('@/components/TaskItem.vue'),
resolvedStore: window.__resolveAlias('@/stores/taskStore.js'),
devPort: window.__viteMeta.port
})""")
exp2 = {
"plugins": ["vue", "@tailwindcss/vite"],
"resolvedComponent": "src/components/TaskItem.vue",
"resolvedStore": "src/stores/taskStore.js",
"devPort": 5173,
}
cases.append({"name": "vite_alias_and_plugin_config", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: Tailwind v4 @theme CSS variables & @layer base computed styles
act3 = page.evaluate("""() => {
const rootStyle = getComputedStyle(document.documentElement);
const bodyStyle = getComputedStyle(document.body);
const chipStyle = getComputedStyle(document.getElementById('brand-chip'));
return {
tokenBrand: rootStyle.getPropertyValue('--color-brand').trim(),
tokenRadius: rootStyle.getPropertyValue('--radius-xl').trim(),
bodyBg: bodyStyle.backgroundColor,
bodyColor: bodyStyle.color,
chipBg: chipStyle.backgroundColor,
chipRadius: chipStyle.borderRadius
};
}""")
exp3 = {
"tokenBrand": "#3b82f6",
"tokenRadius": "1rem",
"bodyBg": "rgb(248, 250, 252)",
"bodyColor": "rgb(15, 23, 42)",
"chipBg": "rgb(59, 130, 246)",
"chipRadius": "16px",
}
cases.append({"name": "tailwind_v4_theme_variables", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: Scaffold CLI matrix & core project files
act4 = page.evaluate("""() => ({
cliCount: Object.keys(window.__viteMeta.cliTemplates).length,
usesVueTemplate: Object.values(window.__viteMeta.cliTemplates).every(c => c.includes('--template vue')),
entryCount: window.__viteMeta.entryFiles.length,
hasViteConfig: window.__viteMeta.entryFiles.includes('vite.config.js')
})""")
exp4 = {"cliCount": 3, "usesVueTemplate": True, "entryCount": 5, "hasViteConfig": True}
cases.append({"name": "cli_commands_inventory", "expected": exp4, "actual": act4, "passed": act4 == exp4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Tailwind v4 通过 @tailwindcss/vite 插件直接接入 Vite 自动扫描 .vue 文件,不再依赖独立的 JS 配置文件,而是直接在 CSS 中通过 @import "tailwindcss" 与 @theme 块定义主题变量。