You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Vite构建Vue 3插件以支持无构建直接使用

用Vite构建支持script标签直接引入的Vue插件

要实现通过script标签直接引入、无需构建即可使用的Vue插件,需调整Vite构建配置并遵循Vue插件规范,具体步骤如下:

1. 配置Vite库模式

修改vite.config.js,指定构建为库模式,输出适合浏览器直接引入的iife格式,并处理Vue外部依赖:

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

export default defineConfig({
  plugins: [vue()],
  build: {
    lib: {
      entry: './src/index.js', // 插件入口文件路径
      name: 'SimpleDemoComponent', // 全局变量名,对应script引入后window上的对象
      fileName: (format) => `simple-demo-component.${format}.js`,
      formats: ['iife', 'umd'] // 输出iife(适配script标签)和umd格式
    },
    rollupOptions: {
      // 将Vue标记为外部依赖,不打包进产物,使用全局Vue变量
      external: ['vue'],
      output: {
        // 映射外部依赖到全局变量
        globals: {
          vue: 'Vue'
        }
      }
    }
  }
})

2. 编写Vue插件入口文件

在src/index.js中导出带有install方法的对象,这是Vue插件的核心要求:

import SimpleDemoComponent from './components/SimpleDemoComponent.vue'

// 导出符合Vue插件规范的对象
export default {
  install(app) {
    // 全局注册组件
    app.component('SimpleDemoComponent', SimpleDemoComponent)
    // 可在此添加全局指令、原型方法等扩展逻辑
  }
}

3. 构建并使用插件

执行构建命令(如npm run build)生成simple-demo-component.iife.js文件,之后即可按目标方式使用:

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plugin test</title>
  </head>
  <body>
    <div id="app">
      <simple-demo-component />
    </div>
    <script src="https://unpkg.com/vue@latest"></script>
    <script src="./dist/simple-demo-component.iife.js"></script>

    <script>
      const { createApp } = Vue;

      const app = createApp();
      app.use(SimpleDemoComponent); // 使用全局暴露的插件对象
      app.mount("#app");
    </script>
  </body>
</html>

构建后的iife产物会在全局作用域暴露配置中指定的SimpleDemoComponent变量,配合全局引入的Vue即可直接使用。

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:10:36