vue-cli3.0打包组件后不能使用"export default was not found in umd.js

问题描述

使用vue-cli3创建了一个组件,想要封装为第三方库后上传到npm供其他项目使用,但是vue-cli-service build --target lib --name lib1 ./src/lib1.vue打包后的库不能被正常使用,提示错误:

 warning  in ./src/App.vue?vue&type=script&lang=js&
"export 'default' (imported as 'lib1') was not found in 'lib1/dist/lib1.umd.js'
vue.runtime.esm.js?2b0e:601 [Vue warn]: Unknown custom element: <lib1> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

相关代码

lib1-demo项目源码

为了便捷从本地源码目录安装组件库:npm install --save ../lib1
package.json部分

{
  "dependencies": {
    "lib1": "file:../lib1",
    "vue": "^2.5.17"
  }
}

src/App.vue

<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <lib1></lib1>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import lib1 from 'lib1/dist/lib1.umd.js'
// import lib1 from 'lib1/src/lib1.vue'   // 此方式正常
console.log(lib1)  // 输出为undefined

export default {
  name: 'app',
  components: {
    HelloWorld,
    lib1
  }
}
</script>

你期待的结果是什么?实际看到的错误信息又是什么?

当lib1-demo项目npm run serve启动后命令行提示警告信息:

 warning  in ./src/App.vue?vue&type=script&lang=js&
"export 'default' (imported as 'lib1') was not found in 'lib1/dist/lib1.umd.js'

浏览器控制台输出:

[HMR] Waiting for update signal from WDS...

undefined

vue.runtime.esm.js?2b0e:601 [Vue warn]: Unknown custom element: <lib1> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found in
---> <App> at src/App.vue
       <Root>
阅读 21.8k
5 个回答

此问题是由于npm install <组件库的源码所在路径>导致的,上传到npm后再安装就可以了。
package.json:

{
  "dependencies": {
    "lib1": "file:../lib1",
    "vue": "^2.5.17"
  }
}

具体原理还不清楚,若有知道的同学请指点!

遇到同问题,参考这篇文章解决的
问题原因可以去原文看下,我贴下解决方法

npm install --save-dev @babel/plugin-transform-modules-umd

babel.config.js

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
  ],
  plugins: ['@babel/plugin-transform-modules-umd'], //主要是这个
};

这样umd包就不用npm publish也能在本地实时引入测试了

lib1.umd.js

这个是什么

你的lib1是一个组件,从你提供的报错来看,就是说你没有注册这个组件,而且从你提供的代码来看,你也是将lib写成一个组件,那么你就只能import lib from './lib1/src/lib.vue'。如果你想在一个js文件中注册一个组件,那么在这个js文件中你应该如此写:

import Vue from 'vue'

Vue.component('lib',{
   template:`<div>这是一个组件</lib>`
})

然后引入这个js文件的时候,你也不用在components:{}里注册这个组件了。建议还是多看看文档组件知识。我有些不太理解你打包后,去引入打包后的js文件这一行为。

楼主有解决方案了吗

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题