Vue3插件报错‘does not provide an export named 'default'’,如何正确导出?
Vue3 插件导出报错问题排查与解决
问题概述
首次开发Vue3插件,编写代码后在main.ts中引入时出现导出错误,无法继续调试组件内容。
现有代码
alert.js 文件
import { createApp } from 'vue' import AlertComponent from './Alert.vue' const Alert = {} Alert.install = (app) => { const instance = createApp(AlertComponent).mount(document.createElement('div')) app.config.globalProperties.$myAlert = (msg) => { document.body.appendChild(instance.$el) // alert logic instance.type = 'alert' instance.msg = msg instance.isShow = true instance.instance = instance } }
main.ts 导入代码
.... import { Alert } from './components/alert.js' .... createApp(App).use(Alert).use(vuetify).mount('#app')
Alert.vue 文件
<script setup lang="ts"> const props = defineProps({ type: String, msg: String, title: String }) </script> <v-alert closable type=type title=title text=msg ></v-alert>
报错信息
The requested module '/src/components/alert.js?t=1691582652693' does not provide an export named 'default'
已尝试的无效操作
- 在
alert.js末尾添加export default Alert;,未解决问题 - 在
const Alert = {}前加export,问题依旧 - 已使用大括号包裹导入,无效果
解决步骤
1. 修正插件导出匹配问题
Vue3支持命名导出和默认导出两种方式,需保证导入与导出语法一致:
方案一:使用命名导出
修改alert.js,直接在定义时导出命名对象:
import { createApp } from 'vue' import AlertComponent from './Alert.vue' // 直接导出命名对象 export const Alert = {} Alert.install = (app) => { const instance = createApp(AlertComponent).mount(document.createElement('div')) app.config.globalProperties.$myAlert = (msg) => { document.body.appendChild(instance.$el) instance.type = 'alert' instance.msg = msg instance.isShow = true instance.instance = instance } }
此时main.ts中的import { Alert } from './components/alert.js'写法无需修改,可正常匹配。
方案二:使用默认导出
修改alert.js末尾添加默认导出:
import { createApp } from 'vue' import AlertComponent from './Alert.vue' const Alert = {} Alert.install = (app) => { const instance = createApp(AlertComponent).mount(document.createElement('div')) app.config.globalProperties.$myAlert = (msg) => { document.body.appendChild(instance.$el) instance.type = 'alert' instance.msg = msg instance.isShow = true instance.instance = instance } } // 添加默认导出 export default Alert;
同时修改main.ts的导入语句,去掉大括号:
import Alert from './components/alert.js'
2. 修正组件模板绑定语法
原Alert.vue中属性未使用响应式绑定,会被解析为字符串,需添加冒号修正:
<v-alert closable :type="type" :title="title" :text="msg" ></v-alert>
3. 规范组件状态修改方式
Vue3中props为只读属性,直接修改instance.type等props不符合规范,建议在Alert.vue中使用内部响应式状态:
<script setup lang="ts"> import { ref } from 'vue' // 定义内部响应式状态 const type = ref('') const msg = ref('') const isShow = ref(false) // 对外暴露状态供插件调用 defineExpose({ type, msg, isShow }) </script> <v-alert v-model="isShow" closable :type="type" :text="msg" ></v-alert>
同步修改alert.js中的调用逻辑:
app.config.globalProperties.$myAlert = (msg) => { document.body.appendChild(instance.$el) instance.type.value = 'alert' instance.msg.value = msg instance.isShow.value = true }
内容的提问来源于stack exchange,提问作者quilkin
相关产品推荐
相关产品推荐

