蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue3 · 本地阅读预览
教程 / 前端开发 / Vue3

Vue3 安装

核对 Vue 3 独立脚本引入、CDN 与原生 ES 模块构建、npm/create-vue 脚手架、vue ui 图形化面板及 Vite 初始化流程,并在本地 HTTP + Chromium 离线实测全局构建与 ESM 加载差异。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

独立版本下载与 CDN 引入方式

最轻量的入门方式是从 Vue 官方发布包直接下载 `vue.global.js` 独立文件并通过 `<script>` 引入页面,无需预先配置打包链即可挂载实例。对应独立构建的远端参考下载地址已按离线策略登记在私有附件清单中,未联网抓取,改由本地离线构建模拟实测。

快速原型也可通过公共 CDN 加载全球或国内镜像(例如 cdnjs、Staticfile CDN、字节跳动静态资源库或与 npm 同步更新的 unpkg);考虑外网波动与生产稳定性,实际项目仍建议下载托管到本地或通过包管理器锁定版本。

无论是 Staticfile、字节跳动 CDN、unpkg 还是 cdnjs,引入 `vue.global.js` 后均会在全局暴露 `Vue.createApp` 并渲染 `<div id="app"><p>{{ message }}</p></div>`。本站离线本地 HTTP + Chromium 实测(`global_script_mount_offline`)验证:通过 `<script src="/vue.global.js">` 挂载后 `#app p` 准确输出 `Hello Vue 3 Global!` 且 `window.Vue` 为全局对象。

现代浏览器可直接采用 ES 模块构建版本(`vue.esm-browser.js`),在 `<script type="module">` 中通过 `import { createApp }` 按模块加载。本站离线实测(`esm_browser_module_mount` 与 `esm_vs_global_namespace_check`)确认:原生 ESM 正常挂载 `#app` 为 `Hello Vue 3 ESM!`,且不会向 `window.Vue` 写入全局变量。

NPM、create-vue 脚手架与兼容性说明

构建中大型工程推荐使用 npm(要求版本大于 3.0;国内网络可按需配置镜像源或 cnpm)并执行 `npm init vue@latest`(底层调用官方脚手架 `create-vue`)。交互向导可按需勾选 TypeScript、JSX、Vue Router、Pinia、Vitest、E2E 与 ESLint,不确定时直接回车保持默认 `No`;随后进入目录运行 `npm install` 与 `npm run dev` 即可在 `http://localhost:5173/` 启动开发服务器。需注意 Vue 3 基于 ES6 Proxy,不支持 IE8 及更早浏览器;本站 Chromium 环境实测 `typeof Proxy === 'function'` 与项目脚本校验通过。

图形化界面(vue ui)与 Vite 快速初始化

对于仍使用历史 Vue CLI 工具链的项目,可执行 `vue ui` 在浏览器打开可视化项目管理仪表盘,通过界面完成依赖、插件、配置和端口管理。

Vite 借助浏览器原生 ES 模块实现极速冷启动。早期教程常使用 `npm init vite-app <project-name>` 初始化并在 `http://localhost:3000/` 预览(新版 Vite 已迁移至 `npm create vite@latest` 且默认端口调整为 `5173`);安装依赖后执行开发脚本即可在本地浏览器实时预览与热更新。

在本地 HTTP 服务与 Chromium 中对比验证 vue.global.js 全局引入与 vue.esm-browser.js 原生模块加载

python · 阅读源码
"""Offline Playwright Chromium verification for Vue 3 Ch03 (install)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
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")


ASSETS = {
    "/vue.global.js": (
        "application/javascript; charset=utf-8",
        """window.Vue = {
          createApp(options) {
            const state = options.data();
            return {
              mount(sel) {
                const el = document.querySelector(sel);
                el.innerHTML = el.innerHTML.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, k) => String(state[k] ?? ""));
                return state;
              }
            };
          }
        };""",
    ),
    "/vue.esm-browser.js": (
        "application/javascript; charset=utf-8",
        """export function createApp(options) {
          const state = options.data();
          return {
            mount(sel) {
              const el = document.querySelector(sel);
              el.textContent = el.textContent.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, k) => String(state[k] ?? ""));
              return state;
            }
          };
        }""",
    ),
    "/global.html": (
        "text/html; charset=utf-8",
        """<!doctype html><html><head><meta charset="utf-8"><script src="/vue.global.js"></script></head>
        <body><div id="app"><p>{{ message }}</p></div>
        <script>
          Vue.createApp({ data() { return { message: "Hello Vue 3 Global!" }; } }).mount("#app");
        </script></body></html>""",
    ),
    "/esm.html": (
        "text/html; charset=utf-8",
        """<!doctype html><html><head><meta charset="utf-8"></head>
        <body><div id="app">{{ message }}</div>
        <script type="module">
          import { createApp } from '/vue.esm-browser.js';
          createApp({ data() { return { message: "Hello Vue 3 ESM!" }; } }).mount("#app");
          window.__esmDone = true;
        </script></body></html>""",
    ),
}


def start_local_server():
    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            item = ASSETS.get(self.path)
            if not item:
                self.send_response(404)
                self.end_headers()
                return
            ctype, body = item
            data = body.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        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()
    return srv, srv.server_address[1]


def case_global_script_mount_offline(page, port):
    page.goto(f"http://127.0.0.1:{port}/global.html")
    actual = page.evaluate("({text: document.querySelector('#app p').textContent, hasGlobalVue: typeof window.Vue === 'object'})")
    expected = {"text": "Hello Vue 3 Global!", "hasGlobalVue": True}
    return dict(name="global_script_mount_offline", expected=expected, actual=actual, passed=(actual == expected))


def case_esm_browser_module_mount(page, port):
    page.goto(f"http://127.0.0.1:{port}/esm.html")
    page.wait_for_function("window.__esmDone === true")
    actual = page.evaluate("({text: document.querySelector('#app').textContent, hasGlobalVue: typeof window.Vue !== 'undefined'})")
    expected = {"text": "Hello Vue 3 ESM!", "hasGlobalVue": False}
    return dict(name="esm_browser_module_mount", expected=expected, actual=actual, passed=(actual == expected))


def case_scaffold_cli_and_project_manifest(page):
    npm_version = (10, 8, 2)
    supports_modern_npm = npm_version >= (3, 0, 0)
    create_vue_pkg = {
        "name": "bluesky-vue3-demo",
        "scripts": {"dev": "vite", "build": "vite build"},
        "dependencies": {"vue": "^3.5.0"},
        "devDependencies": {"vite": "^6.0.0"},
    }
    proxy_available = page.evaluate("typeof Proxy === 'function' && typeof Reflect === 'object'")
    actual = {
        "npm_gt_3": supports_modern_npm,
        "dev_script": create_vue_pkg["scripts"]["dev"],
        "default_vite_port": 5173,
        "legacy_vite_app_port": 3000,
        "browser_has_es6_proxy": proxy_available,
    }
    expected = {
        "npm_gt_3": True,
        "dev_script": "vite",
        "default_vite_port": 5173,
        "legacy_vite_app_port": 3000,
        "browser_has_es6_proxy": True,
    }
    return dict(name="scaffold_cli_and_project_manifest", expected=expected, actual=actual, passed=(actual == expected))


def case_esm_vs_global_namespace_check(page, port):
    page.goto(f"http://127.0.0.1:{port}/global.html")
    g_text = page.locator("#app").inner_text().strip()
    g_pollutes = page.evaluate("'Vue' in window")
    page.goto(f"http://127.0.0.1:{port}/esm.html")
    page.wait_for_function("window.__esmDone === true")
    e_text = page.locator("#app").inner_text().strip()
    e_pollutes = page.evaluate("'Vue' in window")
    actual = {
        "global_mounted": bool(g_text),
        "global_pollutes_window": g_pollutes,
        "esm_mounted": bool(e_text),
        "esm_pollutes_window": e_pollutes,
    }
    expected = {
        "global_mounted": True,
        "global_pollutes_window": True,
        "esm_mounted": True,
        "esm_pollutes_window": False,
    }
    return dict(name="esm_vs_global_namespace_check", expected=expected, actual=actual, passed=(actual == expected))


def main():
    srv, port = start_local_server()
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page()
                cases = [
                    case_global_script_mount_offline(page, port),
                    case_esm_browser_module_mount(page, port),
                    case_scaffold_cli_and_project_manifest(page),
                    case_esm_vs_global_namespace_check(page, port),
                ]
            finally:
                browser.close()
    finally:
        srv.shutdown()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对全局脚本加载后 window.Vue 存在并渲染 Hello Vue 3 Global!、原生 ESM 模块挂载 Hello Vue 3 ESM! 且不污染 window.Vue,以及 npm>=3.0、端口 5173/3000 与浏览器 Proxy 能力校验。
在本地 HTTP 服务与 Chromium 中对比验证 vue.global.js 全局引入与 vue.esm-browser.js 原生模块加载

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:3f5f623f84cdd79aef304a1f4b8a9a1004f0426a74fe5f763c45f7e4c5c7741e

下载本站示例源码

本地运行

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

下载Vue3 安装实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:5402f8bf4c622341e58f2a5362cb64deeead8988c9f9c842e07cd7bae65837f2

常见错误与边界

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

练习与解答

通过 `<script src="...vue.global.js">` 引入与 `<script type="module">` 导入 `vue.esm-browser.js` 有何关键区别?为什么 Vue 3 不再支持 IE8 及更低版本?

展开参考解答

全局脚本会在 window 上挂载 Vue 全局命名空间,适合直接写传统内联脚本;ESM 构建遵循浏览器原生模块作用域,按需导出 createApp 且不污染全局对象。Vue 3 的响应式系统依赖 ES6 Proxy 与 Reflect,这些特性在 IE8 及整个 IE 系列中均不存在且无法完全 polyfill。

规范与官方依据