今年國慶期間尤雨溪公布了Vue 3.0的源碼,代碼庫是用TypeScript寫的。
現(xiàn)有項(xiàng)目還未開始支持TS(下面全用簡稱),支持TS這件事忽然變得迫在眉睫了。
項(xiàng)目基本依賴包版本
vue 2.5.22
vue-cli 3.0.0
需要安裝的依賴包
npm install typescript @vue/cli-plugin-typescript --save-dev
npm install vue-class-component vue-property-decorator --save-dev
npm install @vue/eslint-config-typescript --save-dev
- typescrpt // 必須的
- @vue/cli-plugin-typescript // vue-cli 3 需要安裝
- vue-class-component 官方出品 | 支持類聲明的方式寫組件,提供了Vue、Component等
- vue-prototype-component 社區(qū)出品 | 深度依賴了vue-class-component,拓展出了更多操作符:@Prop、@Emit、@Inject、@Model、@Provide、@Watch
- @vue/eslint-config-typescript // 保持代碼整潔eslint不能少 <-- 版本問題安裝失敗 暫時(shí)pass
tsconfig.json 配置文件
// 官方推薦配置
{
"compilerOptions": {
// 與 Vue 的瀏覽器支持保持一致
"target": "es5",
// 這可以對(duì) `this` 上的數(shù)據(jù)屬性進(jìn)行更嚴(yán)格的推斷
"strict": true,
// 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake:
"module": "es2015",
"moduleResolution": "node"
}
}
重啟本地服務(wù)
No inputs were found in config file 'tsconfig.json'. Specified 'include' paths were '["src/**/*.ts","src/**/*.tsx","src/**/*.vue","packages/**/*.ts","packages/**/*.tsx","packages/**/*.vue"]' and 'exclude' paths were '["node_modules"]'.
報(bào)了個(gè)錯(cuò),解決方案, 在include包含的路徑下新建一個(gè).ts結(jié)尾的空文件即可通過編譯
一個(gè)簡單支持TS的小組件
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import otherComponent from '../../components/otherComponent.vue'
// import otherComponent from '@/components/otherComponent'
...
</script>
輕松愉快的寫個(gè)小demo,然后會(huì)發(fā)現(xiàn)@不能用了,必須要用相對(duì)路徑引用,并且必須帶上.vue的后綴
讓TS識(shí)別.vue
然而上面的小demo其實(shí)也是跑不起的,因?yàn)門ypeScript 默認(rèn)并不支持 *.vue 后綴的文件。
在src路徑下新建一個(gè)my-property(名字隨便取).d.ts的配置文件
import Vue from 'vue'
declare module '*.vue' {
export default Vue
}
這里告訴TS遇到.vue后綴的文件,要讓Vue模塊來處理。
強(qiáng)類型更嚴(yán)格
現(xiàn)有項(xiàng)目使用了axios、vue-router、element-ui等,代碼中使用未聲明過的方法或者變量都是會(huì)報(bào)錯(cuò)的,例this.$route
使用TS的模塊補(bǔ)充功能加一下需要的聲明,慶幸現(xiàn)在大型的組件庫或者使用人數(shù)多的一些插件都已經(jīng)寫好了聲明文件了(到相應(yīng)npm包里.d.ts結(jié)尾的文件里可以看一下哦)。
// 還是剛才的my-property.d.ts文件
declare module 'vue/types/vue' {
// 聲明為 Vue 補(bǔ)充的東西
interface Vue {
$axios: any // 偷懶寫法 解決this.$axios報(bào)錯(cuò)
}
}
// 把用到的包都引一下
declare module 'vue-i18n'
declare module 'axios'
declare module 'vue-router'
declare module 'element-ui'
到這里現(xiàn)有項(xiàng)目跑起來是沒有問題了,具體用TypeScript寫組件時(shí)遵循官網(wǎng)API,這樣就可以愉快在老項(xiàng)目里玩新語言啦。