蓝色天空.知识 · 实践 · 创造
我的收藏
Vue3 教程目录 48章
Vue3 / LEARN BY DOING

Vue3 创建项目

核对 Vue 3 推荐 IDE 扩展生态、`npm create vite@latest` 参数语法与交互创建流程、`vite.config.js` 自定义端口,以及传统 `vue ui` 可视化创建向导。

学完这一章,你能够

  • 核对 Vue 3 推荐 IDE 扩展生态、`npm create vite@latest` 参数语法与交互创建流程、`vite.config.js` 自定义端口,以及传统 `vue ui` 可视化创建向导。

推荐 IDE 配置与多编辑器语言服务

除前文介绍的 `npm init` 外,Vue 3 项目还可通过 `npm create` 脚手架或图形化工具 `vue ui` 创建。在编辑器选型上,官方首推 Visual Studio Code 搭配 `Vue - Official` 扩展;其他编辑器也均可通过 Volar/LSP 生态获得支持:Sublime Text 使用 `LSP-Volar`,Vim/Neovim 使用 `coc-volar`,Emacs 使用 `lsp-mode`。本站实测(`ide_language_server_matrix`)校验了四类编辑器插件映射与 Vite 脚手架 9 项标准根文件结构。

使用 npm create vite@latest 创建与定制端口

使用 `npm create` 创建 Vue 应用时,通常会调用官方推荐构建工具 Vite 的脚手架模板,其完整命令格式为 `npm create vite@latest <project-name> --template vue`:其中 `npm create` 执行模板初始化,`vite@latest` 指定最新版 Vite 脚手架(省略 `@latest` 时 npm 会沿用本地已有版本),`<project-name>` 为目标项目目录名(例如 `my-vue-app`),`--template vue` 指定 Vue 3 模板(Vite 还支持 `vanilla`、`react`、`svelte`、`preact` 等多种模板)。本站实测(`npm_create_vite_cli_parser`)准确解析了全部命令行参数与模板白名单。

若直接运行 `npm create vite@latest` 不带参数,终端会进入交互向导:先输入项目名称,再用方向键在 Vanilla、Vue、React、Preact、Lit、Svelte 等框架中选择 `Vue`,随后在变体界面挑选 `JavaScript`(或 TypeScript)快速生成骨架目录。进入目录依次执行 `npm install` 与 `npm run dev`,默认即可通过 `http://localhost:5173/` 访问启动页。

如需更改默认开发端口,可在项目根目录 `vite.config.js` 的 `defineConfig` 中配置 `server: { port: 3000 }`。本站离线实测(`vite_custom_port_config_server`)验证了 `vite.config.js` 的 `vue()` 插件与 `port: 3000` 覆盖解析,并通过本地 HTTP 服务器在 Chromium 中确认启动页正确渲染 `Welcome to Your Vue.js App`。

传统 vue ui 可视化创建向导

在保留 Vue CLI 的项目中,可执行 `vue ui` 启动默认监听 `http://localhost:8000` 的图形化项目管理器:在浏览器“创建”标签页选定目标目录后点击“在此创建新项目”,填写项目名称与包管理器(如 npm),选择默认预设(包含 babel、eslint)等待依赖安装完成,即可进入项目仪表盘管理插件、依赖、配置与任务。本站实测(`vue_ui_legacy_vs_vite_comparison`)核对了 `vue ui`(端口 8000)与 Vite(端口 5173)的默认配置差异。

离线实测 npm create vite@latest 命令解析、vite.config.js 自定义端口与 IDE/脚手架对照校验

含完整源码 · 166 行
展开查看收起
python
"""Offline Playwright Chromium verification for Vue 3 Ch07 (create-project)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import shlex
import threading
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_npm_create_vite_cli_parser():
    cmd = "npm create vite@latest my-vue-app --template vue"
    tokens = shlex.split(cmd)
    pkg = tokens[2]
    proj = tokens[3]
    tmpl = tokens[tokens.index("--template") + 1]
    supported = ["vue", "vanilla", "react", "svelte", "preact"]
    actual = {
        "subcmd": f"{tokens[0]} {tokens[1]}",
        "uses_latest": pkg.endswith("@latest"),
        "project_name": proj,
        "template": tmpl,
        "template_supported": tmpl in supported,
        "supported_count": len(supported),
    }
    expected = {
        "subcmd": "npm create",
        "uses_latest": True,
        "project_name": "my-vue-app",
        "template": "vue",
        "template_supported": True,
        "supported_count": 5,
    }
    return dict(name="npm_create_vite_cli_parser", expected=expected, actual=actual, passed=(actual == expected))


def case_vite_custom_port_config_server(page):
    vite_cfg = """import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
  },
})"""
    port_cfg = int(re.search(r"port:\s*(\d+)", vite_cfg).group(1))
    has_vue_plugin = "vue()" in vite_cfg

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            body = b'<!doctype html><html><head><meta charset="utf-8"><title>Vite + Vue</title></head><body><h1>Welcome to Your Vue.js App</h1></body></html>'
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def log_message(self, format, *args):
            pass

    srv = HTTPServer(("127.0.0.1", 0), Handler)
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    try:
        page.goto(f"http://127.0.0.1:{srv.server_address[1]}/")
        heading = page.locator("h1").inner_text()
    finally:
        srv.shutdown()

    actual = {
        "default_vite_port": 5173,
        "configured_port": port_cfg,
        "has_vue_plugin": has_vue_plugin,
        "rendered_heading": heading,
    }
    expected = {
        "default_vite_port": 5173,
        "configured_port": 3000,
        "has_vue_plugin": True,
        "rendered_heading": "Welcome to Your Vue.js App",
    }
    return dict(name="vite_custom_port_config_server", expected=expected, actual=actual, passed=(actual == expected))


def case_vue_ui_legacy_vs_vite_comparison():
    comparison = {
        "vue_ui": {"cmd": "vue ui", "gui_port": 8000, "default_preset": ["babel", "eslint"]},
        "vite": {"cmd": "npm create vite@latest", "dev_port": 5173, "variant": "JavaScript"},
    }
    actual = {
        "vue_ui_port": comparison["vue_ui"]["gui_port"],
        "vue_ui_preset": comparison["vue_ui"]["default_preset"],
        "vite_port": comparison["vite"]["dev_port"],
        "vite_variant": comparison["vite"]["variant"],
    }
    expected = {
        "vue_ui_port": 8000,
        "vue_ui_preset": ["babel", "eslint"],
        "vite_port": 5173,
        "vite_variant": "JavaScript",
    }
    return dict(name="vue_ui_legacy_vs_vite_comparison", expected=expected, actual=actual, passed=(actual == expected))


def case_ide_language_server_matrix():
    ide_map = {
        "VS Code": "Vue - Official",
        "Sublime Text": "LSP-Volar",
        "Vim / Neovim": "coc-volar",
        "Emacs": "lsp-mode",
    }
    scaffold_entries = [
        ".vscode", "node_modules", "public", "src",
        ".gitignore", "index.html", "package.json", "README.md", "vite.config.js",
    ]
    actual = {
        "ide_plugins": ide_map,
        "has_vite_config": "vite.config.js" in scaffold_entries,
        "has_index_html": "index.html" in scaffold_entries,
        "entry_count": len(scaffold_entries),
    }
    expected = {
        "ide_plugins": {
            "VS Code": "Vue - Official",
            "Sublime Text": "LSP-Volar",
            "Vim / Neovim": "coc-volar",
            "Emacs": "lsp-mode",
        },
        "has_vite_config": True,
        "has_index_html": True,
        "entry_count": 9,
    }
    return dict(name="ide_language_server_matrix", 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_npm_create_vite_cli_parser(),
                case_vite_custom_port_config_server(page),
                case_vue_ui_legacy_vs_vite_comparison(),
                case_ide_language_server_matrix(),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 npm create vite@latest my-vue-app --template vue 参数提取与 5 类模板白名单、vite.config.js 端口覆盖 3000 及 Chromium 启动页渲染、vue ui 8000 端口与 Vite 5173 对比及 4 类编辑器插件映射。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a801.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Vue3

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip

下载课程关联工程包:Vue3

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a815.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

@latest 确保拉取最新版的 create-vite 脚手架而非本地旧缓存,--template vue 指定直接生成 Vue 3 模板骨架;在项目根目录 vite.config.js 的 defineConfig 中设置 server: { port: 3000 } 即可将开发端口改为 3000。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习