背景
使用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>
解决
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'