Vue + ts 全局组件挂载(附:生成环境失效问题)

本文介绍了在Vue项目中,如何在TypeScript环境下进行全局组件的注册,并解决在生产环境中组件名被压缩导致失效的问题。通过修改webpack配置禁用代码压缩或使用组件的静态属性来保持组件名的稳定性。此外,还提供了按需引入组件的建议。
摘要由CSDN通过智能技术生成

前言

以前使用vue 时,在main.js中使用Vue.component 实现全局挂载,加上ts环境后 就换了种写法。下面跟大家分享一下。

代码

main.ts
import Vue from "vue";
import Components from "./components/index.ts"

Vue.use(Components);

index.ts

在 components目录下,创建index.ts 主要用来引入全局组件。

import { VueConstructor } from 'vue'
// 全局组件
import InfoTip from "@/components/public/InfoTip.vue";

const components = [
  InfoTip,
];

const component = {
  install: (Vue: VueConstructor) => {
    components.forEach((component) => {
      Vue.component(component.name, component);
    })
  }
}
export default component

InfoTip.vue
<script lang="ts">
import { Component, Vue, Prop, Emit } from 'vue-property-decorator'

@Component({
  name: 'InfoTip',
})
export default class InfoTip extends Vue {}
</script>

以上全局组件挂载的时候,在development 开发环境 中使用时可用,然而在生产环境使用 组件失效。目前解决以下方案有两种。

  • webpack 的配置参数 optimization.minimize 默认为true,用于压缩打包后的js。而压缩后component.name的组件名也因此改变了。将该参数改为fasle,就可以使用了。
module.exports = {
...
chainWebpack: (config) => {
	// 默认为true,效果就是压缩js代码。
	config.optimization.minimize(false);
}
...
}
  • 将上述的index.tscomponent.name 改用 另名 entryName 代替,同时 组件中定义该名并赋值为name的值,最后在vue-prototype.d.ts 中定义即可。
index.ts
import { VueConstructor } from 'vue'
// 全局组件
import InfoTip from "@/components/public/InfoTip.vue";

const components = [
  InfoTip,
];

const component = {
  install: (Vue: VueConstructor) => {
    components.forEach((component) => {
      Vue.component(component.entryName, component);
    })
  }
}
export default component

InfoTip.vue
<script lang="ts">
import { Component, Vue, Prop, Emit } from 'vue-property-decorator'

@Component({
  name: 'InfoTip',
})
export default class InfoTip extends Vue {
	public static entryName = 'InfoTip'
}
</script>
vue-prototype.d.ts
declare module "vue/types/vue" {
	interface VueConstructor {
    	entryName: string;
  	}
}

以上就是全部了,自己也是踩了一些坑,最后还有小伙伴不懂操作的可以考虑按需引入~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值