1. 通过 CDN 引入 Vue
    在 index.html 文件中通过 <script> 标签引入 Vue
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vite + Vue</title>
</head>
<body>
  <div id="app"></div>
  <!-- 引入 Vue 3 的完整版本 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</body>
</html>

2. 配置 Vite 将 Vue 设置为外部依赖

在 vite.config.js 中配置 build.rollupOptions.external,告知 Vite 不要将 Vue 打包到构建结果中,而是直接使用全局变量 Vue。

修改 vite.config.js:

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

export default defineConfig({
  plugins: [vue()],
  build: {
    rollupOptions: {
      external: ['vue'], // 告诉 Rollup 不要打包 Vue
      output: {
        globals: {
          vue: 'Vue', // Vue 的全局变量名(与 CDN 引入的对应)
        },
      },
    },
  },
});

3. 在项目中使用 Vue

由于 Vue 是通过 <script> 标签引入的全局变量,直接使用即可。例如:

main.js

import { createApp } from 'vue'; // 使用全局的 Vue 对象


import App from './App.vue';

const app = createApp(App);
app.mount('#app');

4. 开发环境中的类型支持

为了让 TypeScript 或 IDE 提供正确的类型提示,你可以安装 Vue 的类型定义包:

npm install -D @types/vue