按需引入文件时报错,提示Cannot read property 'name' of undefined

开发vue插件报错

最近有个需求,想要封装一套自己的组件内部使用,通用组件通过对iview二次封装,专业的自己开发,前期我搭建环境之后,封装了一个iview的input组件,本地调用没问题。后面进过npm run build以及npm pack只有本地生成了一个tgz包,然后我再另外一个项目中引入。结果报错了,详情见下。这里假设自己封装的项目为A,引入A的项目为B。

A中封装的组件

<template>
  <Input class="fss-input" :placeholder='placeHolder'></Input>
</template>

<style lang="less" scoped>
.fss-input {
  width: 200px;
}
</style>

<script>
import { Input } from 'iview'
export default {
  name: 'fss-input',
  props: {
    placeHolder: {
      type: String,
      default: '敲几个字呗...'
    }
  },
  components: {
    Input
  }
}
</script>

下面是A中包装上面的组件作为vue插件使用的代码

import FssInput from './components/input'

const components = [
  FssInput
]

//这边我是参考element和iview的方式写的
const install = function(Vue, opts = {}) {
  components.map(component => {
    console.log('name', component.name)
    Vue.component(component.name, component)
  })
}

// auto install
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

const API = {
  install,
  ...components
}

module.exports.default = module.exports = API

B通过npm install引入了A,同时为了在B中按需引入A的组件,也做了如下配置

npm install babel-plugin-import --save-dev

// .babelrc
{
  "plugins": ["import", {
      "libraryName": "FssFrontComponent", //换成"fss-front-component"情况一样
      "libraryDirectory": "src/components"
    }]
}

下面是B中引入A的代码

<template>
  <div class="hello">
    <fss-input></fss-input>
  </div>
</template>

<script>
import { FssInput } from 'fss-front-component'
export default {
  name: 'HelloWorld',
  components: {
    [FssInput.name]: FssInput
  },
  data () {
    return {
      placeholder: '终于好了。。。'
    }
  }
}
</script>

报错如下图图片描述

我把引入方法改成如下这样后,报错就不同了

import { FssInput } from 'fss-front-component'
export default {
  name: 'HelloWorld',
  components: {
    FssInput
  },
  data () {
    return {
      placeholder: '终于好了。。。'
    }
  }
}

报错:
图片描述

晚上很多教程都是自己写的单个组件,我们这边是需要一个组件库的,只不过暂时只有一个input而已,大家如果有好的方法解决请不吝告知,多谢~

阅读 12.6k
1 个回答

算是解决了,主要是之前在webpack中的配置问题,入口文件搞错了。但是目前能够做到的是全局引入,后续需要尝试改成按需引入。

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