背景
使用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
內(nèi)只能識別.ts
和.js
文件, 不知道如何處理.png
文件, 只需讓Typescript
知道怎么處理.png
文件即可
// index.d.ts
// 聲明一下 .png文件即可
declare module '*.png'