【ts】ts项目引入文件报红,进行全局类型声明的方法

vue3项目中使用ts,如果要引入的文件没有相应的类型声明文件,那么你需要为每个文件创建对应的类型声明文件
例如:我要引入index.vue文件。

  1. 那么就需要在src目录下创建index.vue.d.ts 的文件,要确保文件名与需要创建类型声明的模块文件名一致。
  2. 在 index.vue.d.ts 文件中编写对应的类型声明。根据你的模块内容,可以为模块的导出对象创建一个接口,并为每个属性指定相应的类型。
// index.vue.d.ts
declare module '@/Layout/index.vue' {
    
    
  import {
    
     ComponentOptions } from 'vue';
  
  const componentOptions: ComponentOptions;
  
  export default componentOptions;
}

但是一个项目中不可能只引入一个文件,每个文件都要创建类型声明文件的话,太繁琐太冗余了。

就要用统一的方式解决这个问题:使用类型声明文件的全局声明,在项目中创建一个名为global.d.ts的全局类型声明文件,就可以为整个项目中的文件添加类型声明

// global.d.ts
declare module '*.vue' {
    
    
  import {
    
     ComponentOptions } from 'vue';

  const componentOptions: ComponentOptions;

  export default componentOptions;
}

猜你喜欢

转载自blog.csdn.net/bbt953/article/details/132378732