關於ts-loader 中的 appendTsSuffixTo淺見

引言

項目使用的 Vue + TypeScript + webpack,其中TypeScript 使用的是ts-loader
因爲使用了vue單文件組件,因此ts-loader配置了appendTsSuffixTo: [/\.vue$/]
可是發如今使用thread-loadercache-loader加速構建時,會報Could not find file: '*.vue.ts'的錯誤。可是項目中並無*.vue.ts的文件。vue

關於appendTsSuffixTo

官方文檔給出的解釋:appendTsxSuffixTo webpack

A list of regular expressions to be matched against filename. If filename matches one of the regular expressions, a .ts or .tsx suffix will be appended to that filename.
This is useful for *.vue file format for now. (Probably will benefit from the new single file format in the future.)。

大體意思是,會給對應文件添加個.ts.tsx後綴。這也就是報錯的找不到vue.ts的由來。
讓咱們來梳理下ts編譯vue 單文件組件的過程:git

vue 單文件組件中假如使用了 lang="ts"ts-loader須要配置 appendTsSuffixTo: [/\.vue$/],用來給 .vue文件添加個 .ts後綴用於編譯。

可是這個.ts文件並不實際存在,因此在使用cache-loader時,會報找不到這個文件的錯誤。github

解決方案

因爲報的是找不到文件錯誤,那咱們就把 TypeScript代碼.vue中移出來。
使用一個單獨的ts文件,而後vue在引用這個ts文件web

xxx.vue文件:typescript

<template>
<div>
</div>
</template>

<script lang="ts" src="./xxx.ts"></script>

<style>
</style>

xxx.ts文件:express

export default {
}

參考

  1. threader-loader例子
  2. Vue single file , after add lang="ts",Module build failed: Error: Could not find file: '*.vue'.
  3. ts-loader
  4. awesome-typescript-loader
相關文章
相關標籤/搜索