在ts项目中使用了图片压缩的第三方库,js-image-compressor,通过import导入提示无法找到声明

解决办法

  1. 在src目录下新建类型声明文件(因为ts.config.ts中的include字段默认有"src/**/*.d.ts"路径) type.d.ts

  2. type.d.ts 添加对该第三库的模块声明,并导出

    type.d.ts
      declare module 'image-compressor.js' {
        const content: any
        /// 这里的 content 可以根据自己的需要,添加需要的类型,这的话可以让 ts 更好的提示
        /**
        type content = {
          test: string
        }
       */
        export = content
      }
    
    
  3. tsconfig.json include字段(和compilerOptions同级)增加配置,
    "include": ["src"]

遇到这种问题可以先试一下安装对应第三库是否有对应的types声明文件,没有提供则按照上面的方法来处理。

npm install -D @types/xxx


类似的,在项目开发过程中,在vue文件使用import导入.vue文件获.ts文件,如果提示“找不到模块“xxx”或其相应的类型声明。”,直接粘贴下面的代码到tyoe.d.ts文件中

Show Code

	declare module '*.vue' {
	  import { DefineComponent } from 'vue'
	  const component: DefineComponent<{}, {}, any>
	  export default component
	}
	// 环境变量 TypeScript的智能提示
	interface ImportMetaEnv {
	  VITE_APP_TITLE: string;
	  VITE_APP_PORT: string;
	  VITE_APP_BASE_API: string;
	}
	interface ImportMeta {
	  readonly env: ImportMetaEnv;
	}

Posted on 2024-08-31 21:33  易烊千玺圈外女友  阅读(568)  评论(0)    收藏  举报