vue文件内引入图片, vetur提示报错

背景

使用vue-cli3+typescript+vscode+vetur插件来写vue项目时, 在vue组件引入图片时, vetur会提示报错, 当时项目可以正常使用

问题

<script lang="ts">
// 以下两行报错
// Cannot find module '../assets/checkbox.dark.big.png'.Vetur(2307)
import darkImage from "../assets/checkbox.dark.big.png";
import lightImage from "../assets/checkbox.light.big.png";

import { Vue, Component, Prop, Emit } from "vue-property-decorator";
@Component
export default class TodoItem extends Vue {
  ...
}
</script>

解决

在stackoverflow搜了一下很快有了答案

The problem is that you confuse TypeScript level modules and Webpack level modules.
In Webpack any file that you import goes through some build pipeline.
In Typescript only .ts and .js files are relevant and if you try to import x from file.png TypeScript just does not know what to do with it, webpack config is not used by TypeScript.
In your case you need to separate the concerns, use import from for TypeScript/EcmaScript code and use require for Webpack specifics.
You would need to make Typescipt ignore this special Webpack require syntax with a definition like this in a .d.ts file:
declare function require(string): string;
This will make Typescript ignore the require statements and Webpack will be able to process it in the build pipeline.

简言之就是Typescript内只能识别.ts.js文件, 不知道如何处理.png文件, 只需让Typescript知道怎么处理.png文件即可

// index.d.ts

// 声明一下 .png文件即可
declare module '*.png'

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容