vue-cli 中使用 TypeScript


學以致用,這篇文章是對在 vue-cli 中使用 TypeScript 的一次小結。

環境

npm

// typescript
npm install typescript --save-dev

// ts-loader
npm install ts-loader --save-dev

webpack.base.conf.js

module.exports = {
  // 修改入口文件
  entry: './src/main.ts',
  // 引入 ts/tsx 文件時不必后綴 
  resolve: {
    extensions: ['.js', '.vue', '.json', '.ts', '.tsx'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  module: {
    // 對 ts 使用 ts-loader
    {
      test: /\.tsx?$/,
      exclude: /node_modules/,
      use: [
        "babel-loader",
        {
          loader: "ts-loader",
          options: { appendTsxSuffixTo: [/\.vue$/] }
        }
      ]
    }
	// ...其他
  }
}

創建一個 .d.ts 文件讓 TypeScript 識別 .vue 文件,在此項目中,我放到了 src/typings 文件夾下:

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

根目錄下添加 tsconfig.json 配置文件,配置參數參考:https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Compiler Options.html ,項目內有一份配置,就不貼出來了。

JavaScript 校驗

很遺憾,如果你使用 TypeScript,在vue-cli(2.9.1) 里並不能使用 ESlint 校驗 .vue 文件了,很常見的一個報錯:

在 .vue 文件內,並不識別 .d.ts 聲明文件內的類型。

ESlint 不能用,TSlint 怎么樣?
折騰了一會,在 .vue 文件內也有坑(可能是功力不夠),最后決定先放棄。

webpack.base.conf.js

關於插件

由於在 Vue 中使用 TypeScript 還不是很普及,大部分插件都缺少聲明文件:

此時必須添加新聲明。
不過還好,Vue, Vue Router, Vuex, Element,都提供了相應的聲明文件。

開始修改

.vue 文件

當然,首先要讓 webpack 識別為 TypeScript 而不是 JavaScript,在 script 標簽上加上 lang="ts":

<template>
// ...
</template>
<script lang="ts">
// ...
<script>

有個官方維護的插件 vue-class-component ,可以寫成下面方式:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  // 所有組件選項可以寫這里
})
export default class Hello extends Vue {}

更多的實例可以看 https://github.com/vuejs/vue-class-component
此外,還有另一個基於 vue-class-component 的 vue-property-decorator 插件,提供了如 Watch、Prop、Emit 等修飾器,於是可以寫成下面方式:

import { Component, Vue, Watch, Prop } from 'vue-property-decorator'

@Component
export default class Hello extends Vue {
  @Watch('someValue')
  valueChange(val, oldVal) {}
  
  @Prop()
  propA: number
}

Vue Router

Vue Router 的修改比較容易,在 router/index.ts 內為變量添加相應 interface 即可:

import Vue, { AsyncComponent } from 'vue'
import Router, { RouteConfig, Route, NavigationGuard } from 'vue-router'

import home: AsyncComponent = (): any => import(/* webpackChunkName: "home" */ '@/pages/home/index.vue')
// ... 其他組件

const routers: RouteConfig[] = [
  {
    path: '/home',
    comment: 'home'
  }
  // ...其他 routers
]

如果你想組件內使用 Vue Router 導航鈎子,你必須注冊一次:

import Component from 'vue-class-component'

// Register the router hooks with their names
Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave',
  'beforeRouteUpdate' // for vue-router 2.2+
])

其他插件提供的鈎子,也可以這么使用。
必須在使用之前注冊,我把它放到了 main.ts 里。

Vuex

Vuex 修改相對麻煩一點。

一個簡單的栗子

import Vue from 'vue'

// 需要使用 Vuex 的 interface 
import Vuex, { ActionTree, MutationTree } from 'vuex'

Vue.use(Vuex)

interface State = {
  name: String;
}

const state: State = {
  name: ''
}

const action: ActionTree<State, any> = {
  changName (
    { commit },
    name: String
  ): void {
    commit('CHANGE_NAME', name)
  }
}

const mutations: MutationTree<State> = {
  'CHANGE_NAME' (
    state: State,
    name: String
  ): void {
    state.name = name
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations
})

如果你想在組件里面使用 vuex 的輔助函數,可以使用這個插件 vuex-class 。由於我不習慣使用輔助函數,這里也就不再贅述了。


這里有完整的代碼:https://github.com/jkchao/vue-admin

完。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM